html表使用vba进行抓取

时间:2017-12-18 10:47:45

标签: html vba excel-vba web screen-scraping

我试图从tr标签中获取国家但它只是给了我表格的第一行我如何刮取特定的行

Sub ipsearch()
    Dim x As Integer
    x = 2

    Do Until x = 4000   

        Dim ie As New InternetExplorer    
        ie.navigate "https://whatismyipaddress.com/ip/" & Range("E" & x).Value

        Do    
            DoEvents        
        Loop Until ie.readyState = READYSTATE_COMPLETE

        Dim doc As HTMLDocument    
        Set doc = ie.document    
        Dim sDD As String

        sDD = Trim(doc.getElementsByTagName("td")(, 0).innerText)

        Range("F" & x).Value = sDD    
        x = x + 1    
    Loop

End Sub

enter image description here 蓝色的是我得到的,黄色是我想要的

2 个答案:

答案 0 :(得分:1)

这将是回归"英国"在你的例子中:

Sub ipsearch()
    Dim x As Long
    x = 2

    Do Until x = 4000
        Dim ie As New InternetExplorer
        ie.navigate "https://whatismyipaddress.com/ip/" & "2.99.247.66"

        Do
            DoEvents

        Loop Until ie.readyState = READYSTATE_COMPLETE
        Dim doc As HTMLDocument
        Set doc = ie.document
        Dim sDD As String
        ie.Visible = True

        sDD = Trim(doc.getElementsByTagName("tbody")(1).innerText)
        Range("F" & x).Value = Split(sDD, vbCrLf)(5)

        x = x + 1

    Loop

End Sub

一般来说,编写更好的代码有一些想法。

  • 知道您正在使用的内容真的很棒 - 例如,在屏幕截图中,来自IP的数字来自蓝色上方的行,例如来自"详情为2.99.247.66"。
  • 当您向StackOverflow提供代码时,请务必提及您的代码正在使用的其他库。在你的情况下这两个:

enter image description here

或者确保您的代码使用后期绑定,因此不应添加库。   - 一般情况下,请考虑使用Long,而不是Integer - Why Use Integer Instead of Long?

  • 在提交代码时格式化代码。它看起来好一点。 Ctrl + K 是StackOverflow中的快捷方式。
  • Option Explicit用于VBA。
  • 尝试对问题中的变量进行硬编码。在你的情况下:

"https://whatismyipaddress.com/ip/" & "2.99.247.66"

答案 1 :(得分:1)

给它一个机会。它会获取国家/地区名称并将其放在范围(“A1”)中。

Sub ipsearch()
    Dim HTTP As New XMLHTTP60, html As New HTMLDocument
    Dim post As Object

    With HTTP
        .Open "GET", "https://whatismyipaddress.com/ip/2.99.247.66", False
        .send
        html.body.innerHTML = .responseText
    End With

    For Each post In html.getElementsByTagName("th")
        If InStr(post.innerText, "Country:") > 0 Then [A1] = post.ParentNode.LastChild.innerText: Exit For
    Next post
End Sub

参考添加到库:

1. Microsoft XML,v6.0  ''or the version you have
2. Microsoft HTML Object Library

为了加快速度,请尝试以下方法:

United Kingdom

参考添加到库:

{{1}}

输出:

{{1}}