[英]IE excel vba to fetch data
我需要從網站獲取數據。 網站內容跟隨標簽,我需要提取 href 屬性。
鏈接 rel='canonical' href=' http://www.wingatecinci.com '
為此,我編寫了以下代碼來提取 Excel 中的 href 屬性
Option Explicit
Sub Tester()
Dim IE As New InternetExplorer
Dim i As Long
Dim Cano As String
Range("A1").Value = "Cano"
Set IE = New InternetExplorer
URL = "http://www.wingatecinci.com/"
IE.navigate Url
IE.Visible = True
Do While IE.Busy Or IE.ReadyState <> READYSTATE_COMPLETE
DoEvents
Loop
Cano = IE.document.getElementsByTagName("canonical")(i).innerHTML
Range("A" & i + 2).Value = Cano
End Sub
但是我沒有成功,並且面臨錯誤,請參閱此屏幕截圖http://prntscr.com/kpy9dh任何人都可以查看並幫助我嗎?
您可以為元素添加等待並使用 CSS 屬性選擇器來定位該屬性。 這當前有一個 5 秒的循環來嘗試定位元素。
Option Explicit
Public Sub GetLink()
Dim IE As New InternetExplorer, ele As Object, t As Date
Const MAX_WAIT_SEC As Long = 5
With IE
.Visible = True
.navigate "http://www.wingatecinci.com/"
t = Timer
Do While ele Is Nothing
DoEvents
On Error Resume Next
Set ele = .document.querySelector("[rel='canonical']")
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop
If Not ele Is Nothing Then Debug.Print ele.href
.Quit
End With
End Sub
參考:
這兩行將i
作為變量引用:
Cano = IE.document.getElementsByTagName("canonical")(i).innerHTML
Range("A" & i + 2).Value = Cano
但是您沒有在代碼中的任何地方設置i
的值。 你是想把它放在一個循環中嗎?
此外,這里的“標簽”是<link>
- "canonical"
部分是該標簽的一個屬性,因此您需要在代碼中進一步詳細說明以測試這些:
For Each el In IE.Document.getElementsByTagName("link")
If el.hasAttribute("link") Then
// do something with this element
End If
Next
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.