2016-10-31 38 views
1

從VBA,我試圖訪問網頁中的「用戶名」單元格,以便我可以輸入適當的用戶名。通過VBA從HTML頁面獲取信息

問題是,在頁面的HTML代碼中,我們有多個具有相同名稱的元素,即「LOGON_USERID」,我無法弄清楚如何訪問正確的元素。你可以在圖像的「HTML代碼的一部分」中看到,我嘗試訪問的這一行是突出顯示的那一行,但也有兩個其他元素在它上面具有相同的名稱。

part of the HTML code

我嘗試許多不同的方式(使用不同的方法或變量類型等),但因爲我不熟悉HTML,我不能設法得到我想要的東西。

Sub Pum()  

Dim ie As New InternetExplorer 
'Dim IEDoc As IHTMLElementCollection 
Dim IEDoc As HTMLDocument 
Dim name As Object 
Dim nameList As HTMLInputElement 
Dim WRONGS As DispHTMLElementCollection 
Dim Elems As HTMLElementCollection 
Dim i As Integer 

ie.navigate "thewebsiteinquestion" 


ie.Visible = False 


WaitIE ie 


Set IEDoc = ie.document 
'MsgBox IEDoc.DocumentElement. 
'Elems = IEDoc.getElementsByTagName("INPUT") 
MsgBox TypeName(IEDoc.getElementById("LOGON_USERID").all) 
Set Elems = IEDoc.getElementById("LOGON_USERID") 
'For i = 0 To 5 
MsgBox Elems.Length 
'Next i 
For Each name In Elems.Children 
MsgBox name.nodeName 
MsgBox name.Attributes 
MsgBox name.all 

Next 


'If ((NameStr Isnot Nothing And (NameStr.Length <> 0)) Then 
'If NameStr = "LOGON_USERID" Then 
'If TypeName(IEDoc.all("LOGON_USERID")) = "HTMLInputElement" Then 


    'MsgBox TypeName(IEDoc.all("LOGON_USERID")) 
    'Set names = IEDoc.all.Item("text") 
    'TypeName (InputUsernameTextzone) 
    'Dim Question As IHTMLElement 
    'Question = InputUsernameTextzone.parentElement 
    'MsgBox TypeName(InputUsernameTextzone.parentElement.getAttribute("name")) 
    'InputUsernameTextzone.parentElement 

    'CELLULE.value = "qtc2464" 



    WaitIE ie 


    Set ie = Nothing 
    Set IEDoc = Nothing 

End Sub 

我嘗試了兩種使用不同方法的類似代碼,但我仍然沒有結果。希望你能幫助我。

如果您需要更多信息,請告訴我。

+0

自動化以這種方式可以是一個棘手的業務。特別是如果你不擁有該網站。每次更新網站時,您的代碼都有可能失敗。網站是否發佈了您可以使用的API? –

+0

@ destination-data:嘿,基本上這是我工作的公司的網頁,我的想法是直接使用宏訪問數據,以便更新可以自動完成。我們必須在此頁面上提供唯一的用戶名和密碼。我對APi這個術語並不熟悉,但是在查詢了它的含義之後,我猜想沒有這樣的東西可以使用。 – Seb

回答

0

另外兩個輸入元素是不同類型的(它們是隱藏),所以你可以使用querySelector的屬性type=text找到你想要的元素。

Dim userid As HTMLInputElement 
Set userid = IEDoc.querySelector("input[name='LOGON_USERID'][type='text']") 

If Not userid Is Nothing Then 
    ' Continue with user id element 
Else 
    MsgBox "LOGON_USERID not found on the page" 
End If 
+0

編輯:它的作品!非常感謝。我從字面上對這個8小時發誓我發誓! – Seb

+0

歡迎您! – dee

0

我是一個新手,在這一點,但如果這能幫助別人,這是我做宏觀的簡化版本:

Sub Access_Puma() 

Dim ie As New InternetExplorer 
Dim IEDoc As HTMLDocument 
Dim userid As HTMLInputElement 
Dim userpwd As HTMLInputElement 
      ie.navigate "thewebsitetoaccess" 

ie.Visible = True 


WaitIE ie 

    Set IEDoc = ie.document 

Set userid = IEDoc.querySelector("input[name='LOGON_USERID'][type='text']") 
If Not userid Is Nothing Then 
userid.value = "myusername" 
Else 
MsgBox "LOGON_USERID not found on the page" 
End If 

Set userpwd = IEDoc.querySelector("input[name='LOGON_PASSWD'][type='password']") 
If Not userpwd Is Nothing Then 
userpwd.value = "mypassword" 
Else 
MsgBox "LOGON_PASSWD not found on the page" 
End If 
End Sub