【问题标题】:VBA Selenium isn't returning the first column of data into ExcelVBA Selenium 没有将第一列数据返回到 Excel
【发布时间】:2020-08-11 05:52:22
【问题描述】:

我已经安装了 Selenium,一切正常,除了第一列数据没有从网站返回并发布到 Excel 中。我确定这很简单。任何人,请帮忙。

Sub PullData()

Dim driver As New WebDriver
Dim rowc, cc, columnC As Integer
rowc = 2
driver.Start "chrome"
driver.Get "https://www.cmegroup.com/trading/fx/g10/australian-dollar_quotes_settlements_options.html#optionProductId=8093&optionExpiration=8094-Q0&tradeDate=08%2F10%2F2020"
Application.Wait Now + TimeValue("00:00:10")

'Header
For Each th In driver.FindElementByClass("cmeTable").FindElementByTag("thead").FindElementsByTag("tr")
cc = 1
For Each t In th.FindElementsByTag("th")
Sheet1.Cells(1, cc).Value = t.Text
cc = cc + 1
Next t
Next th

'Body
For Each tr In driver.FindElementByClass("cmeTable").FindElementByTag("tbody").FindElementsByTag("tr")
columnC = 2
For Each td In tr.FindElementsByTag("td")
Sheet1.Cells(rowc, columnC).Value = td.Text
columnC = columnC + 1
Next td
rowc = rowc + 1
Next tr
End Sub

【问题讨论】:

  • 您在 Column1 中启动标题,然后在 Column2 中启动数据。这是故意的吗?
  • 是的,因为我需要为第一列留出空间,这是缺失的。我最初在第 1 列中有它,但结果仍然相同。
  • 每行的第一个单元格是th,而不是td,因此您需要先获取它,然后再遍历剩余的td 元素。
  • 这就是 Header 下的部分正在做的事情,它首先循环 th。标题th 或正文td 的第一列都不会拉。
  • 不,在标题上循环的部分仅在 thead 中找到 th 元素 - 它不会在 tbody 下找到包含在 tr 中的任何 th 跨度>

标签: excel vba selenium scrape


【解决方案1】:

我没有 Selenium,但这里是使用 IE 自动化的基本大纲:

    Dim Explorer As Object, doc, tbls, tr, td
    Set Explorer = GetIEByUrl("https://www.cmegroup.com/trading*") 'function to get an open window by URL
    
    Set doc = Explorer.document
    
    Set tbls = doc.getElementsByTagName("table")
    'look at the first table: get the rows in the table body
    For Each tr In tbls(0).getElementsByTagName("tbody") (0).getElementsByTagName("tr")
        'the first cell is a th
        Debug.Print tr.getElementsByTagName("th")(0).innerText
        'the rest of the cells are td's
        For Each td In tr.getElementsByTagName("td")
            Debug.Print td.innerText
        Next td
        Debug.Print "***********************"
    Next tr

【讨论】:

  • 我刚刚发现没有拉取的数据被描述为class="invisibleElement cmeFixedColumn"。有什么方法可以对此进行编码调整吗?
  • "invisibleElement" 只是一个类名——它在 HTML 中没有特殊意义。以上对我来说很好(使用 IE)
  • 它在 IE 中也适用于我。但是,IE 不稳定,超级慢,并且当我在多个页面上执行时不断崩溃。因此转向 Chrome。
  • 我正在查看您上面的 URL,但没有看到该类名。
  • 我也不能了……嗯。奇怪,我一开始也没看到。在某些时候,它显示为我为上述评论复制/粘贴的内容。无论哪种方式,代码都会提取除标题和正文的第一列“Strike”之外的所有内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多