在excel vba中多次单击网页上的按钮

时间:2017-11-08 18:58:03

标签: excel-vba web-scraping vba excel

我尝试多次单击按钮以完全加载页面。网页包含一个按钮SHOW MORE而不是下一页,因此按钮后面的html编码保持不变。

我正在使用以下excel-vba代码来点击该按钮。它实际上点击了那个按钮,但不是显示下一个结果,而是一遍又一遍地显示相同的结果。

请你告诉我如何做对。提前谢谢!

    **' VARIABLE DECLARATION
    Dim IE As Object
    Dim county As String
    Dim htmlDoc As Object

    ' CREATING OBJECT
    Set IE = CreateObject("internetexplorer.application")

    ' WEBPAGE NAVIGATION
    With IE
    .navigate ("http://www.physiofirst.org.uk/find-physio/search-physio.html")
    .Visible = True
    End With

    ' WAITING FOR WEBPAGE TO LOAD
    Do
    DoEvents
    Loop Until IE.readystate = 4

    ' SEARCHING ALL THE THE INDIVIDUAL STATE PHYSICIANS
    Set htmlDoc = IE.document
    Set searchbarvalue = htmlDoc.getelementsbyclassname("form-control mod-text-display")
    i = 0
    For Each classSearch In searchbarvalue
        searchbarvalue(i).Value = "BRISTOL"
    Next classSearch
    While IE.busy
        DoEvents
    Wend

    Set buttonclick = htmlDoc.getelementsbyclassname("btn btn-search")
    i = 0
    For Each buttonsearch In buttonclick
        buttonclick(i).Click
    Next buttonsearch
    While IE.busy
        DoEvents
    Wend
    Do
    htmlDoc.getelementbyid("load-more-practice").Click
    While IE.busy
    DoEvents
    Wend
    Loop Until htmlDoc.getelementbyid("load-more-practice").Click = True
End Sub**

1 个答案:

答案 0 :(得分:0)

尝试使用Do Until data-page =“1”的代码,因为它从2开始并在完全加载时转到1,并且单击所有Show More。

Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)

Sub test()
Dim IE As Object
Dim county As String
Dim htmlDoc As Object
Dim sURL As String

' CREATING OBJECT
Set IE = CreateObject("internetexplorer.application")

sURL = "http://www.physiofirst.org.uk/find-physio/search-physio.html"
' WEBPAGE NAVIGATION
With IE
.navigate (sURL)
.Visible = True
End With

WaitIE IE, 2000

' SEARCHING ALL THE THE INDIVIDUAL STATE PHYSICIANS
Set htmlDoc = IE.document
Set searchbarvalue = htmlDoc.getElementsByClassName("form-control mod-text-display")
i = 0
For Each classSearch In searchbarvalue
    searchbarvalue(i).Value = "BRISTOL"
Next classSearch

WaitIE IE, 1000

Set buttonclick = htmlDoc.getElementsByClassName("btn btn-search")

buttonclick(0).Click
WaitIE IE, 1000
Set ShowMore = htmlDoc.getElementById("load-more-practice")

Do
ShowMore.Click
WaitIE IE, 2000
Loop Until ShowMore.getAttribute("data-page") = 1

'IE.Quit
'Set IE = Nothing
End Sub

Sub WaitIE(IE As Object, Optional time As Long = 250)
'Code from: https://stackoverflow.com/questions/33808000/run-time-error-91-object-variable-or-with-block-variable-not-set
Dim i As Long
Do
    Sleep time
    Debug.Print CStr(i) & vbTab & "Ready: " & CStr(IE.readyState = 4) & _
                vbCrLf & vbTab & "Busy: " & CStr(IE.Busy)
    i = i + 1
Loop Until IE.readyState = 4 Or Not IE.Busy
End Sub