我正在嘗試使用objElement和objCollection從網站抽取數據。相關和工作代碼如下:VBA:使用objElement和objCollection從網站抽取數據
Sub Step6()
Dim LoanNumX As Long
Dim LastX As String
Dim Phone1X As String
Dim Phone2X As String
Dim PiX As String
Dim TiX As String
Dim myText2 As String
ActiveWorkbook.Save
Range("M2").Select
Do While ActiveCell.Value <> ""
Dim IE As Object
Dim objElement As Object
Dim objCollection As Object
LastX = ActiveCell.Value
ActiveCell.Offset(, -12).Select
BigX = ActiveCell.Value
Phone1X = "N/A"
Phone2X = "N/A"
PiX = "N/A"
TiX = "N/A"
Set IE = CreateObject("InternetExplorer.Application")
IE.Navigate "https://website.com"
Application.StatusBar = "https://website.com is loading. Please wait..."
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
Set objCollection = IE.Document.getElementsbyTagName("input")
A1 = 0
While A1 < objCollection.Length
If objCollection(A1).Name = "networkId" Then
objCollection(A1).Value = "ID"
Else
If objCollection(A1).Name = "password" Then
objCollection(A1).Value = "PW"
Else
If objCollection(A1).Name = "btnLogin" Then
Set objElement = objCollection(A1)
objElement.Click
End If
End If
End If
A1 = A1 + 1
Wend
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
上述代碼功能完整。下面的代碼直接來自上面的代碼後,和出現的問題:
Application.StatusBar = "Search form submission. Please wait..."
Set objCollection = IE.Document.getElementsbyTagName("input")
L = 0
While L < objCollection.Length
If objCollection(L).Name = "account" Then
objCollection(L).Value = BigX
Else
If objCollection(L).Name = "lastName" Then
objCollection(L).Value = LastX
Else
If objCollection(L).Type = "image" Then
Set objElement = objCollection(L)
objElement.Click
End If
End If
End If
L = L + 1
Wend
出於某種原因,上面的代碼被跳過。我沒有說明爲什麼,但是宏從來沒有經過while語句 - 就像L> objCollection.Length從一開始就一樣。如果我踏入這個腳本,它跳躍距離:
While L < objCollection.Length
代碼段如下:
Wend
結果是IE瀏覽器打開時,初始頁面被訪問時,輸入的登錄數據並提交,顯示結果頁面,然後打開另一個IE實例並重復循環。 IE,初始頁面,登錄數據,結果頁面,IE,初始頁面,登錄數據,結果頁面,IE ......所以當我強制宏退出時,最終會遇到大量實例停留在同一頁面上。
我已經嘗試了幾種不同的方法,但至今未能解決問題。
下面是HTML之後,我的數據:
<td><input type="text" name="account" maxlength="9" size="25" value="" onkeypress="accountSelected()" class="inputbox"></td>
<td><input type="text" name="lastName" size="25" value="" onkeypress="lastNameSelected()" class="inputbox"></td>
<input type="image" src="images/search.gif" alt="Search">
任何幫助,不勝感激!另外,我使用的是MS Excel 2007和IE 7.我知道IE 7不支持IE.Document.getElementsbyClassName,所以這個規則可以作爲一個潛在的解決方案。我知道Excel 2007和IE 7都過時了,但我無法更新它們。