【发布时间】: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 元素的“文本”属性。有更快的方法吗?
【问题讨论】:
-
你有什么异常吗?还是只是执行缓慢?如果速度很慢,那么使用
xpath或css搜索元素可能会快一点。 -
也不例外,处理每一行只需要一段时间。
-
请注意,row.find_elements_by_tag_name 非常快。只是 'cells[#].text' 让一切变慢
-
具体来说,每个单元格[#].text 需要 ~.035 秒,每行加起来是 0.245 秒。当我解析很多行时,事情会变得很慢。
-
FWIW,
.text是 Selenium 必须做的计算成本最高的事情之一,因此它会对性能产生一些影响。
标签: python selenium selenium-webdriver html-table webdriver