点击链接后如何导航回来?

时间:2017-10-12 19:56:26

标签: vba excel-vba internet-explorer web-scraping click

我很高兴在vba中使用IE,所以我有时很难纠正我在编写任何代码来从网上抓取数据时所犯的任何错误。我已经编写了一些代码来点击其首页上标题Microsoft computer training videos下的20个链接中的每个视频链接。我希望单击每个链接然后导航回并重复该过程,直到单击所有链接。我在刮刀中定义的类名和标签名称是准确的。我需要做的就是以正确的方式执行该过程。此时我的刮刀正在点击20个链接的最后一个链接,并卡在那里,但不会导航回来。

这是我到目前为止所写的内容。

Sub clicking_links()

    Const surl As String = "http://www.wiseowl.co.uk/videos/"
    Dim IE As New InternetExplorer, iedoc As HTMLDocument
    Dim posts As Object

    With IE
        .Visible = True
        .navigate surl
        Do Until .readyState = READYSTATE_COMPLETE: Loop
        Set iedoc = IE.document
    End With

    For Each posts In iedoc.getElementsByClassName("woVideoListDefaultSeriesTitle")
        posts.getElementsByTagName("a")(0).Click
    Next posts

End Sub

1 个答案:

答案 0 :(得分:2)

尝试以下方法:

Sub clicking_links()

    Const surl As String = "http://www.wiseowl.co.uk/videos/"
    Dim newurl as String
    Dim IE As New InternetExplorer, iedoc As HTMLDocument
    Dim posts As Object
    Dim t As Long, i As Long

    With IE
        .Visible = True
        .navigate surl
        Do Until .readyState = READYSTATE_COMPLETE: Loop
        Set iedoc = .document

        For Each posts In iedoc.getElementsByClassName("woVideoListDefaultSeriesTitle")
            t = t + 1 'count the number of posts
        Next posts

        For i = 1 To t
            Debug.Print i
            newurl = iedoc.getElementsByClassName("woVideoListDefaultSeriesTitle")(i - 1).getElementsByTagName("a")(0).href
            Debug.Print newurl

            .navigate newurl
            Do Until .readyState = READYSTATE_COMPLETE: Loop
            Set iedoc = .document
            'here do your stuff within the new url

            .navigate surl 'back to old url
            Do Until .readyState = READYSTATE_COMPLETE: Loop
            Set iedoc = .document
        Next i

    End With
End Sub