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

使用MS XML 6.0库请求StatMuse投手日志:优化未知URL循环方案

高效解决方案

1. 用搜索接口直接获取玩家ID

暴力遍历ID是最低效的方式,通过搜索玩家姓名定位正确URL,避免无意义请求:

  • 构造搜索URL:https://www.statmuse.com/search?q=MLB+玩家姓名(比如搜索Martín Pérez就是https://www.statmuse.com/search?q=MLB+Martin+Perez)
  • 发送GET请求后,解析返回的HTML,找到格式为/mlb/player/martin-perez-46483的玩家主页链接,从中提取5位ID。

示例优化代码:

Function GetPlayerID(playerName As String) As String
    Dim http As New MSXML2.XMLHTTP60
    Dim html As New HTMLDocument
    Dim searchUrl As String
    Dim link As Object
    
    ' 处理空格为+,构造搜索URL
    searchUrl = "https://www.statmuse.com/search?q=MLB+" & Replace(playerName, " ", "+")
    
    http.Open "GET", searchUrl, False
    http.send
    html.body.innerHTML = http.responseText
    
    ' 遍历链接找玩家主页入口
    For Each link In html.getElementsByTagName("a")
        If InStr(link.href, "/mlb/player/") > 0 Then
            ' 拆分链接提取ID
            Dim parts() As String
            parts = Split(link.href, "-")
            GetPlayerID = parts(UBound(parts))
            Exit Function
        End If
    Next link
    
    GetPlayerID = "" ' 未找到返回空字符串
End Function

2. 优化HTTP请求与资源管理

原代码重复创建对象、未释放资源会加重Excel负担:

  • 复用HTTP对象,避免在循环内反复初始化
  • 每次请求后清理HTML文档对象
  • 添加请求延迟(比如Application.Wait Now + TimeValue("00:00:01")),避免触发反爬,同时降低请求频率

3. 找到ID后立即终止循环

原代码找到正确ID后仍遍历剩余数字,浪费资源:

  • 确认找到目标ID后,执行Exit For跳出循环

4. 优化错误处理与代码健壮性

  • 避免依赖全局变量cc,将玩家姓名作为参数传入CheckUrlExists函数
  • 精准区分404错误与网络错误,避免误判无效URL

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 04:08:14