You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Excel VBA 如何提取指定网页中对应VS标识的所有href链接

示例

原有代码问题说明

你之前的代码没有拿到目标链接主要有两个原因:

  1. 遍历a标签时仅打印了ID和类名,没有获取href属性
  2. 依赖IE浏览器,部分页面元素加载逻辑可能受IE兼容性影响,运行效率低且稳定性差

解决方案

你可以用WinHTTP替代IE请求页面资源,搭配querySelectorAll方法匹配目标链接,实现方案如下:
首先提前在VBA编辑器的「工具-引用」中勾选以下两个库:

  • Microsoft WinHTTP Services, version 5.1
  • Microsoft HTML Object Library

然后使用如下代码:

Sub ScrapeMatchLinks()
    Dim http As New WinHttp.WinHttpRequest
    Dim html As New MSHTML.HTMLDocument
    Dim matchLinks As MSHTML.IHTMLDOMChildrenCollection
    Dim link As MSHTML.HTMLAnchorElement
    Dim url As String
    
    url = "https://www.academiadasapostas.com/stats/competition/brasil/26"
    
    ' 发送请求拉取页面
    With http
        .Open "GET", url, False
        .setRequestHeader "User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
        .send
        If .Status <> 200 Then
            Debug.Print "请求失败,状态码:" & .Status
            Exit Sub
        End If
        html.body.innerHTML = .responseText
    End With
    
    ' 使用CSS选择器匹配所有比赛VS对应的链接:分组下所有带有赛事详情路径的a标签
    Set matchLinks = html.querySelectorAll("#competition-round-group-0 a[href*='/stats/match/']")
    
    ' 遍历输出所有链接
    For Each link In matchLinks
        Debug.Print link.href
    Next link
    
    Set http = Nothing
    Set html = Nothing
End Sub

代码说明

  • 用WinHTTP请求页面无需启动浏览器,运行效率远高于IE操作,也不会受IE停用的影响
  • CSS选择器#competition-round-group-0 a[href*='/stats/match/']的含义是:匹配id为competition-round-group-0的节点下,所有href属性包含/stats/match/的a标签,正好对应所有VS指向的赛事详情链接
  • 加了User-Agent请求头避免网站拦截请求

内容的提问来源于stack exchange,提问作者TiagoSantos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 20:33:03