VBA如何提取href标签下<b>标签内的目标数值?
解决方案:提取特定href下标签的数值
针对你遇到的问题,这里提供3种可行的VBA实现方法,无需依赖类名即可定位目标元素:
方法1:遍历标签匹配href特征
通过遍历页面所有标签,筛选出符合目标href特征的元素,再获取其子标签的文本:
Dim ie As Object Dim aElements As Object Dim aElement As Object Dim targetValue As String Set ie = CreateObject("InternetExplorer.Application") ie.Visible = True ie.Navigate "你的目标网页URL" ' 等待页面完全加载 Do While ie.Busy Or ie.ReadyState <> 4 DoEvents Loop Set aElements = ie.Document.getElementsByTagName("a") ' 遍历匹配href(可根据实际需求调整匹配规则,比如只匹配部分关键词) For Each aElement In aElements ' 精确匹配href,若href是动态的,可改用InStr(aElement.href, "goldvreneli") > 0 这类模糊匹配 If aElement.href = "https://目标网站域名/goldvreneli-20-franken-vreneli/de/44-1/add/CH-GV-20-1897.2-2/1" Then targetValue = aElement.getElementsByTagName("b")(0).innerText MsgBox "提取到的数值:" & targetValue Exit For ' 找到目标后终止循环 End If Next aElement ie.Quit Set ie = Nothing
方法2:用CSS选择器直接定位(简洁高效)
利用CSS选择器直接定位到href匹配的标签下的元素,代码更简洁:
Dim ie As Object Dim targetElement As Object Dim targetValue As String Set ie = CreateObject("InternetExplorer.Application") ie.Visible = True ie.Navigate "你的目标网页URL" Do While ie.Busy Or ie.ReadyState <> 4 DoEvents Loop ' 精确匹配href的CSS选择器,若需模糊匹配可改用 a[href*='goldvreneli'] b Set targetElement = ie.Document.querySelector("a[href='/goldvreneli-20-franken-vreneli/de/44-1/add/CH-GV-20-1897.2-2/1'] b") If Not targetElement Is Nothing Then targetValue = targetElement.innerText MsgBox "提取到的数值:" & targetValue End If ie.Quit Set ie = Nothing
方法3:用XPath定位
通过XPath表达式精准定位目标元素,适合复杂的DOM结构场景:
Dim ie As Object Dim doc As Object Dim targetNode As Object Dim targetValue As String Set ie = CreateObject("InternetExplorer.Application") ie.Visible = True ie.Navigate "你的目标网页URL" Do While ie.Busy Or ie.ReadyState <> 4 DoEvents Loop Set doc = ie.Document ' XPath表达式:匹配指定href的<a>标签下的<b>标签 Set targetNode = doc.SelectSingleNode("//a[@href='/goldvreneli-20-franken-vreneli/de/44-1/add/CH-GV-20-1897.2-2/1']/b") If Not targetNode Is Nothing Then targetValue = targetNode.Text MsgBox "提取到的数值:" & targetValue End If ie.Quit Set ie = Nothing
注意事项
- 若目标href是动态生成的,不要用精确匹配,改用模糊匹配:比如方法1中用
InStr(aElement.href, "goldvreneli") > 0,方法2中用a[href*='goldvreneli'] b(*表示包含指定字符串) - 必须等待页面完全加载完成后再执行元素定位,否则会出现找不到元素的错误
- 如果页面中有多个符合条件的元素,需要进一步细化匹配规则(比如结合父元素的特征)
内容的提问来源于stack exchange,提问作者kewy
相关产品推荐
相关产品推荐

