4

在此处输入图像描述

我想编写一个宏来获取网页中的搜索结果链接。我是这样写的

Sub webpage()

Dim internet As InternetExplorer

Dim internetdata As HTMLDocument

Dim internetlink As Object

Dim internetinnerlink As Object

Set internet = CreateObject("InternetExplorer.Application")

internet.Visible = True

internet.Navigate ("URL")

Do While internet.Busy

  DoEvents

Loop

Do Until internet.ReadyState = READYSTATE_COMPLETE

  DoEvents

Loop

Set internetdata = internet.Document

Set internetlink = internetdata.getElementsByTagName("a")

i = 1

For Each internetinnerlink In internetlink

ActiveSheet.Cells(i, 2) = internetinnerlink.href

i = i + 1

Next internetinnerlink

End Sub

上面的代码获取网页中的所有链接,但我只需要搜索结果链接。我上传了一张图片,如果那是我的网页,我只需要获取搜索结果链接而不是所有链接。请帮我解决这个问题

4

1 回答 1

6

试试这个代码

Sub webpage()

    Dim internet As Object
    Dim internetdata As Object
    Dim div_result As Object
    Dim header_links As Object
    Dim link As Object
    Dim URL As String

    Set internet = CreateObject("InternetExplorer.Application")
    internet.Visible = True

    URL = "https://www.google.co.in/search?q=how+to+program+in+vba"
    internet.Navigate URL

    Do Until internet.ReadyState >= 4
        DoEvents
    Loop

    Application.Wait Now + TimeSerial(0, 0, 5)

    Set internetdata = internet.Document
    Set div_result = internetdata.getelementbyid("res")


    Set header_links = div_result.getelementsbytagname("h3")

    For Each h In header_links
        Set link = h.ChildNodes.Item(0)
        Cells(Range("A" & Rows.Count).End(xlUp).Row + 1, 1) = link.href
    Next

    MsgBox "done"
End Sub
于 2013-11-14T17:24:11.730 回答