【问题标题】:Getting text of a table quickly in Selenium在 Selenium 中快速获取表格的文本
【发布时间】:2015-02-19 22:44:32
【问题描述】:

我正在尝试使用 Selenium 将表中的许多列解析为字典,但我所拥有的似乎很慢。我正在使用 python、Selenium 2.0 和 webdriver.Chrome()

table = self.driver.find_element_by_id("thetable")
    # now get all the TR elements from the table
    all_rows = table.find_elements_by_tag_name("tr")

    # and iterate over them, getting the cells
    for row in all_rows:
        cells = row.find_elements_by_tag_name("td")
        # slowwwwwwwwwwwwww
        dict_value = {'0th': cells[0].text,
                 '1st': cells[1].text,
                 '2nd': cells[2].text,
                 '3rd': cells[3].text,
                 '6th': cells[6].text,
                 '7th': cells[7].text,
                 '10th': cells[10].text}

问题似乎在于获取每个 td 元素的“文本”属性。有更快的方法吗?

【问题讨论】:

  • 你有什么异常吗?还是只是执行缓慢?如果速度很慢,那么使用xpathcss 搜索元素可能会快一点。
  • 也不例外,处理每一行只需要一段时间。
  • 请注意,row.find_elements_by_tag_name 非常快。只是 'cells[#].text' 让一切变慢
  • 具体来说,每个单元格[#].text 需要 ~.035 秒,每行加起来是 0.245 秒。当我解析很多行时,事情会变得很慢。
  • FWIW,.text 是 Selenium 必须做的计算成本最高的事情之一,因此它会对性能产生一些影响。

标签: python selenium selenium-webdriver html-table webdriver


【解决方案1】:

另一种选择。

如果稍后(循环之后),您不需要 selenium 为您提供的交互性 - 您可以将页面的当前HTML source code 传递给以速度着称的lxml.html。示例:

import lxml.html

root = lxml.html.fromstring(driver.page_source)
for row in root.xpath('.//table[@id="thetable"]//tr'):
    cells = row.xpath('.//td/text()')
    dict_value = {'0th': cells[0],
                  '1st': cells[1],
                  '2nd': cells[2],
                  '3rd': cells[3],
                  '6th': cells[6],
                  '7th': cells[7],
                  '10th': cells[10]}

【讨论】:

  • @PearSquirrel 太棒了!与纯硒方法相比,您是否测量过它的工作速度快了多少?谢谢。
  • 过去需要 ~5 秒来处理,现在需要 ~.1 秒
  • 即使只有两个索引 (0,1),我也会遇到索引超出范围错误有什么想法吗?我的表有足够的数据。
  • 真的很酷的东西。我喜欢这进展得有多快。从 20 秒到 2 秒。
猜你喜欢
  • 2019-10-12
  • 2021-01-15
  • 1970-01-01
  • 2021-05-20
  • 2013-07-29
  • 2019-02-19
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
相关资源
最近更新 更多