vba点击网站

时间:2018-01-10 18:25:46

标签: html vba

您好我正在尝试点击网页上的超链接:https://factfinder.census.gov/faces/nav/jsf/pages/community_facts.xhtml

我想点击链接:

  

2016年美国社区调查

     

人口和住房估计(年龄,性别,种族,住户和住房......)

我试过了

   'start a new subroutine called SearchBot
    Sub SearchBot()

'dimension (declare or set aside memory for) our variables
Dim objIE As InternetExplorer 'special object variable representing the IE browser
Dim aEle As HTMLLinkElement 'special object variable for an <a> (link) element
Dim y As Integer 'integer variable we'll use as a counter
Dim result As String 'string variable that will hold our result link
Dim Link As Object
Dim ElementCol As Object

'initiating a new instance of Internet Explorer and asigning it to objIE
Set objIE = New InternetExplorer

'make IE browser visible (False would allow IE to run in the background)
objIE.Visible = True

'navigate IE to this web page (a pretty neat search engine really)
objIE.navigate "https://factfinder.census.gov/faces/nav/jsf/pages/community_facts.xhtml"

'wait here a few seconds while the browser is busy
While objIE.readyState <> 4
DoEvents
Wend

'in the search box put cell "A2" value
objIE.document.getElementById("cfsearchtextbox").Value = _
  Sheets("Sheet1").Range("A2").Value

'click the 'Add/Remove Geographies' button
objIE.document.getElementById("communityfactssubmit").Click

'wait here a few seconds while the browser is busy
While objIE.readyState <> 4
DoEvents
Wend


    Set ElementCol = objIE.document.getElementsByTagName("a")
    For Each Link In ElementCol
    If Link.innerHTML = "Demographic and Housing Estimates (Age, Sex, Race,Households and Housing, ...)" Then
        Link.Click
    End If
    Next Link

它不起作用。但我可以使用此方法点击“反馈”,“常见问题解答”等链接。请帮忙。谢谢!!!

这是链接的路径,我不知道我是否可以使用它来获取链接而不是试图找到文本

cf-content&gt; div:nth-​​child(2)&gt; div.links&gt; ul:nth-​​child(4)&gt; li> div>一个

1 个答案:

答案 0 :(得分:0)

这对我有用:当您填充链接集合时,页面未完全加载,因此您需要在此之前添加一个短暂的等待。

Sub SearchBot()

    Dim objIE As InternetExplorer
    Dim aEle As Object 'HTMLLinkElement
    Dim y As Integer
    Dim result As String
    Dim Link As Object
    Dim ElementCol As Object

    Set objIE = New InternetExplorer
    objIE.Visible = True
    objIE.navigate "https://factfinder.census.gov/faces/nav/jsf/pages/community_facts.xhtml"

    WaitFor objIE

    objIE.document.getElementById("cfsearchtextbox").Value = "Draper City"
    objIE.document.getElementById("communityfactssubmit").Click

    WaitFor objIE
    Application.Wait Now + TimeSerial(0, 0, 2) '<<<<<< wait 2 sec

    Set ElementCol = objIE.document.getElementsByTagName("a")
    For Each Link In ElementCol
        Debug.Print Link.innerText
        If Link.innerText Like "Demographic and Housing Estimates*" Then
            Link.Click
            Exit For
        End If
    Next Link

End Sub

'utility Sub: wait for page to load
Sub WaitFor(IE As Object)
    While IE.readyState <> 4
        DoEvents
    Wend
End Sub