Excel VBA+Selenium网页抓取:多thead/tbody元素数据获取求助
Excel VBA + Selenium Chrome 抓取多thead/tbody表格数据解决方案
原代码仅能获取第一个thead和tbody的核心问题是:使用了单数形式的FindElementByTag,该方法只会返回页面中匹配的第一个元素。要获取所有同标签元素,必须使用复数形式的FindElementsByTag生成元素集合,再通过遍历或索引访问目标元素。
修改后的完整代码
Sub test2() Dim driver As New WebDriver Dim rowc, cc, columnC As Integer Dim theads As WebElements, tbodyElements As WebElements Dim currentRow As Integer rowc = 2 currentRow = 22 driver.Start "chrome" driver.Get "https://www.betexplorer.com/football/argentina/primera-nacional/" ' 遍历处理所有thead元素 Set theads = driver.FindElementByClass("stats-table-container").FindElementsByTag("thead") For theadIndex = 1 To theads.Count cc = 1 For Each th In theads(theadIndex).FindElementsByTag("tr") For Each t In th.FindElementsByTag("th") Munka1.Cells(currentRow, cc).Value = t.Text cc = cc + 1 Next t currentRow = currentRow + 1 Next th Next theadIndex ' 遍历处理所有tbody元素 Set tbodyElements = driver.FindElementByClass("stats-table-container").FindElementsByTag("tbody") For tbodyIndex = 1 To tbodyElements.Count For Each tr In tbodyElements(tbodyIndex).FindElementsByTag("tr") columnC = 1 For Each td In tr.FindElementsByTag("td") Munka1.Cells(rowc, columnC).Value = td.Text columnC = columnC + 1 Next td rowc = rowc + 1 Next tr Next tbodyIndex driver.Quit ' 关闭Chrome进程,避免残留窗口 End Sub
关键修改说明
- 获取元素集合:将
FindElementByTag("thead")和FindElementByTag("tbody")替换为FindElementsByTag(复数形式),得到页面中所有匹配的thead/tbody元素集合。 - 遍历集合:通过
For循环遍历集合索引(Selenium VBA中集合索引从1开始),确保每个thead/tbody都被处理。 - 指定单个元素(可选):若仅需处理第二个thead/tbody,可直接通过索引访问,无需遍历整个集合,示例代码如下:
' 仅处理第二个thead If theads.Count >= 2 Then cc = 1 For Each th In theads(2).FindElementsByTag("tr") For Each t In th.FindElementsByTag("th") Munka1.Cells(currentRow, cc).Value = t.Text cc = cc + 1 Next t currentRow = currentRow + 1 Next th End If ' 仅处理第二个tbody If tbodyElements.Count >= 2 Then For Each tr In tbodyElements(2).FindElementsByTag("tr") columnC = 1 For Each td In tr.FindElementsByTag("td") Munka1.Cells(rowc, columnC).Value = td.Text columnC = columnC + 1 Next td rowc = rowc + 1 Next tr End If
内容的提问来源于stack exchange,提问作者Karesz
相关产品推荐
相关产品推荐

