从网页中提取文本,前面有唯一的文本,但没有唯一的类或标记



我试图从一组相似的网页中提取一个唯一的数字。它们都非常相似,但我使用的当前代码使用MSXML2.XMLHTTP,并标识给定类或标记中的文本。

问题是这些网页略有不同,因此代码无法根据Item标准可靠地从所有网页中提取。而且,页面上有许多相同的类和标记,因此没有任何唯一的标识。

但是,有一段唯一的文本("ISIN代码:"(,然后我想要的ISIN编号在下一行中。我听说过Ids解析,但找不到这些/不知道这种方法是如何工作的。

我想提取的信息是"GB00B6Y7NF43":

<tr>
<th class="align-left">ISIN code:</th>
<td> GB00B6Y7NF43 </td>
</tr>

这是我现在使用的大部分代码,用于使用Item(…(方法查找页面上的其他信息。我不知道我的代码本身是否正确,但到目前为止,如果你按项目(0(或项目(1(等指定,它会正确地提取信息。

Dim request As Object
Dim response As String
Dim html As New HTMLDocument
Dim td As Object
Dim website As String
Dim charge As Variant
With Worksheets("Sheet1")
website = Range("A14").Value
End With
Set request = CreateObject("MSXML2.XMLHTTP")
request.Open "GET", website, False
request.send
response = StrConv(request.responseBody, vbUnicode)
html.body.innerHTML = response
Worksheets("Information").Activate
r = r + 2:
Cells(r, 3) = html.getElementsByClassName("header-row").Item(0).innerText
Cells(r, 5) = html.getElementsByTagName("td").Item(0).innerText
Cells(r, 4) = html.getElementsByClassName("icon-link pdf-icon").Item(1).href

有没有其他方法/编码风格/对我的代码进行调整来做到这一点?

我可以使用dimie/appIe和类似的方法,但到目前为止,这些方法在pc上比简单地处理html文本更棘手,速度也更慢。

它是表中的最后一个子级,因此可以链接lastchild调用

html.querySelector("[summary='More fund information']").children(0).lastchild.lastchild.innertext

所以

Option Explicit
Public Sub test()
Dim html As HTMLDocument
Set html = New HTMLDocument
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://www.hl.co.uk/funds/fund-discounts,-prices--and--factsheets/search-results/f/fidelity-asia-class-w-accumulation/key-features", False
.send
html.body.innerHTML = .responseText
End With
Debug.Print html.querySelector("[summary='More fund information'] ").Children(0).LastChild.LastChild.innerText
End Sub

随着时间的推移,一种较慢但可能更稳健的方法可能是收集表格标题,找到具有所需ISIN文本的标题,然后取NextSibling(td(节点。

Option Explicit
Public Sub test()
Dim html As HTMLDocument
Set html = New HTMLDocument
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "https://www.hl.co.uk/funds/fund-discounts,-prices--and--factsheets/search-results/f/fidelity-asia-class-w-accumulation/key-features", False
.send
html.body.innerHTML = .responseText
End With
Dim i As Long, nodes As Object
Set nodes = html.querySelectorAll("[summary='More fund information'] th")
For i = 0 To nodes.Length - 1
If nodes.Item(i).innerText = "ISIN code:" Then
Debug.Print nodes.Item(i).NextSibling.innerText
Exit For
End If
Next
End Sub

最新更新