2017-12-18 354 views
-1

IM試圖從tr標籤的國家,但它只是給我的表的第一行我怎麼刮的特定行HTML表格刮使用VBA

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

這是後話,將在您的例子返回「聯合王國」:

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中的快捷方式。
  • 對於VBA使用Option Explicit
  • 嘗試硬編碼問題中的變量。你的情況:

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

+0

謝謝你我會和我一起嘗試你的版本 – yusuf

2

給這個鏡頭。它會把你的國名帶到Range(「A1」)。

Sub ipsearch() 
    Dim IE As New InternetExplorer, html As HTMLDocument 
    Dim post As Object 

    With IE 
     .Visible = False 
     .navigate "https://whatismyipaddress.com/ip/2.99.247.66" 
     Do Until .readyState = READYSTATE_COMPLETE: Loop 
     Set html = .document 
    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 
    IE.Quit 
End Sub 

引用添加到庫中:

1. Microsoft Internet Controls 
2. Microsoft HTML Object Library 

,並使其方式速度更快,請嘗試以下之一:

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