使用VBA爬取网站球员姓名列表出现运行时错误438如何解决
错误原因
运行时错误“438”的触发原因是getElementsByClassName返回的是元素集合对象,你直接对整个集合调用.innerText属性,集合本身不支持该属性,因此触发报错。
此外代码还存在两处可优化的隐患:
- 未判断球员容器
HTMLPlayers是否存在有效元素,若页面未加载到对应类名的节点,直接访问HTMLPlayers(0)也会触发报错 - 循环体中重复调用
getElementsByClassName获取名字节点,属于重复请求可提前提取
修正后代码
Option Explicit Sub Kickbase() Dim IE As New SHDocVw.InternetExplorer Dim HTMLdoc As MSHTML.HTMLDocument Dim HTMLPlayers As MSHTML.IHTMLElementCollection Dim HTMLfirstNames As MSHTML.IHTMLElementCollection Dim i As Integer Dim firstName As String IE.Visible = True IE.Navigate "https://play.kickbase.com/transfermarkt/kaufen" Do While IE.ReadyState <> READYSTATE_COMPLETE Or IE.Busy Loop ' 等待页面动态渲染完成 Application.Wait (Now + TimeValue("0:00:10")) Set HTMLdoc = IE.Document Set HTMLPlayers = HTMLdoc.getElementsByClassName("players") ' 先判断球员容器是否存在 If HTMLPlayers.Length > 0 Then ' 提前获取所有firstName节点 Set HTMLfirstNames = HTMLPlayers(0).getElementsByClassName("firstName") For i = 0 To HTMLfirstNames.Length - 1 ' 对集合中第i个元素取innerText,而不是对整个集合取值 If Not HTMLfirstNames(i) Is Nothing Then firstName = Trim(HTMLfirstNames(i).innerText) Else firstName = "no_value" End If Debug.Print firstName Next i Else Debug.Print "未找到球员容器节点,请检查页面加载状态或类名是否正确" End If ' 清理对象 Set HTMLfirstNames = Nothing Set HTMLPlayers = Nothing Set HTMLdoc = Nothing IE.Quit Set IE = Nothing End Sub
关键改动说明
- 循环前先判断
HTMLPlayers集合长度,避免空引用报错 - 提前一次性获取所有名字节点集合
HTMLfirstNames,减少重复DOM查询 - 访问
.innerText前指定集合下标HTMLfirstNames(i),对应单个元素调用属性 - 补充了IE对象的退出和内存清理逻辑,避免后台残留IE进程
- 在等待加载的判断逻辑中新增
IE.Busy校验,避免页面未完成交互就执行后续逻辑
内容的提问来源于stack exchange,提问作者Poseidon
相关产品推荐
相关产品推荐

