使用VBA从谷歌检索信息,试图build立一个停止时,谷歌不能按预期工作

Sub test() Dim IE As New InternetExplorer Dim city$, state$ Dim i As Integer Dim dd As Variant Dim doc As HTMLDocument 'variable for document or data which need to be extracted out of webpage Set doc = IE.document i = 2 'start row 'Setting the variables city = Cells(i, 1).Value 'City variable for search state = Cells(i, 2).Value 'State variable for search Do Until city = "" city = Cells(i, 1).Value 'City variable for search state = Cells(i, 2).Value 'State variable for search 'Search google for state and county URL = "www.google.com/?safe=active&ssui=on#q=" + city + "+" + state + "+county&safe=active&ssui=on" IE.navigate URL IE.Visible = False Do DoEvents Loop Until IE.readyState = READYSTATE_COMPLETE Application.Wait (Now() + TimeValue("00:00:005")) ' For internal page refresh or loading dd = doc.getElementsByClassName("_eF")(0).innerText ' Now, trim the name to take the State out dd = Left(dd, WorksheetFunction.Search(",", dd) - 1) 'set county value Cells(i, 3).Value = dd 'MsgBox dd i = i + 1 'Setting the next variables city = Cells(i, 1).Value 'City variable for search state = Cells(i, 2).Value 'State variable for search Loop MsgBox "The macro has finished running" End Sub 

到目前为止,这是我得到感谢用户@BruceWayne的帮助

然而,有时谷歌没有提供必要的信息,如果这个城市没有一个县或者太模糊。 我需要macroslogging这个并继续下去。 但是,每次尝试进行if语句或失败检查时,macros都会停止并提示debugging窗口,因为它试图检索doc.getElementsByClassName("_eF")(0).innerText

我可以做什么来检查,如果doc.getElementsByClassName("_eF")(0).innerText是否存在,如果它不logging这一点,并继续前进?

谢谢!

从集合中检索元素的方法是基于零的索引,但.Length属性是基于一个的。 换句话说,单个元素集合中的第一个在位置0但长度为1

 if cbool(doc.getElementsByClassName("_eF").LENGTH) then _ dd = doc.getElementsByClassName("_eF")(0).innerText 

我刚刚处理了这个问题。 我写了一个函数来testing我想要的元素是否在屏幕上。 function如下。 我相信你可以根据你的需要修改它。

 Function ScreenTest(oDoc as Object, sLookUp As String) As Boolean 'tests to see if a particular screen is loaded by passing the element name associated with what you would expect to see on the screen 'pass oDoc has your IE document Dim sTest As String On Error Resume Next sTest = oDoc.getElementsByName(sLookUp).item(0).Value If Err.Number <> 0 Then ScreenTest = False Else: ScreenTest = True On Error GoTo 0 End Function 

要把这个放在你的代码中,这样做:

 If ScreenTest(doc, "_eF") Then dd = doc.getElementsByClassName("_eF")(0).innerText ' Now, trim the name to take the State out dd = Left(dd, WorksheetFunction.Search(",", dd) - 1) 'set county value Cells(i, 3).Value = dd 'MsgBox dd i = i + 1 End If '... continue with rest of code