简体   繁体   English

IE excel vba 获取数据

[英]IE excel vba to fetch data

I need to fetch data from a website.我需要从网站获取数据。 The website content following tag, and I need to extract href attribute.网站内容跟随标签,我需要提取 href 属性。

link rel='canonical' href=' http://www.wingatecinci.com '链接 rel='canonical' href=' http://www.wingatecinci.com '

For this, I have written following code to extract href attribute in Excel为此,我编写了以下代码来提取 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

But I did not get the success, and facing error see this screenshot http://prntscr.com/kpy9dh Can any one look into this and help me out??但是我没有成功,并且面临错误,请参阅此屏幕截图http://prntscr.com/kpy9dh任何人都可以查看并帮助我吗?

You can add a wait in for the element and use a CSS attribute selector to target the attribute.您可以为元素添加等待并使用 CSS 属性选择器来定位该属性。 This currently has a loop of 5 seconds to try and locate the element.这当前有一个 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

References:参考:

  1. Microsoft HTML Object Library微软 HTML 对象库
  2. Microsoft Internet Controls微软互联网控制

These two lines reference i as a variable:这两行将i作为变量引用:

Cano = IE.document.getElementsByTagName("canonical")(i).innerHTML
Range("A" & i + 2).Value = Cano

But you haven't set the value of i anywhere in your code.但是您没有在代码中的任何地方设置i的值。 Did you mean to put this inside a loop perhaps?你是想把它放在一个循环中吗?


Also the "tag" here is <link> - the "canonical" part is an attribute of that tag, so you need to further elaborate in your code to test for these:此外,这里的“标签”是<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM