我正在尝试使用带有 VBA 的 HTML webscraping 从网页中提取数据。我在其他网站上取得了成功,但是这个网站在标记为 tspan 的代码行中有数据,我似乎无法从中获取数据。
HTML 代码如下所示(抱歉,代码很长,不确定什么是相关的和不相关的):
<div class="Classname">
<svg width ="100%" height="100%" fill="code" stroke="100%" stroke="code" viewBox="numbers" class="undefined">
<polygon fill="transparent" points="numbers"></polygon?
<text y="100" dy="#s">
<tspan x="100" text-anchor="middle">1</tspan>
我想要的值是之前最后一行中的 1。在导航到正确的网页等后,我用来提取它的代码是:
Dim text As String
text=IE.document.GetElementsByClassname("Classname")(0).GetElementsByTagname("tspan")(0).innertext
我还尝试了类名“未定义”的位置,因为它出现在 svg 代码行中。无论哪种方式,我都会收到错误 91。
编辑:我现在尝试了嵌套的 GetElementsByTagName,仍然出现错误
text=IE.document.GetElementsByClassname("C")(0).GetElementsByTagname("svg")(0).GetElementsByTagname("polygon")(0).GetElementsByTagname("text")(0).GetElementsByTagname("tspan")(0).innertext
最佳答案
这里有更直接更快捷的方法
Option Explicit
Public Sub GetData()
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.Navigate2 "https://www.tipranks.com/stocks/mmm/stock-analysis"
While .Busy Or .readyState < 4: DoEvents: Wend
Do 'could use timed loop here to handle infinite looping risk
Set elem = .document.querySelectorAll("tspan")
Loop While elem.Length = 0
Debug.Print elem.item(0).innerText
.Quit
End With
End Sub
关于html - 如何在 VBA 网页抓取中从 HTML 代码中提取 <tspan> 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56553062/