从网页 - Excel VBA获取链接/ URL

时间:2013-11-14 11:19:47

标签: excel-vba vba excel

enter image description here

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

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

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

1 个答案:

答案 0 :(得分:5)

试试此代码

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