您好,我正在尝试对不同的元素 tr 执行 for 循环,每个元素都包含 td 和要提取的信息,当我执行循环时,它返回错误: TypeError:列表索引必须是整数或切片,不是 WebElement
lines = driver.find_elements_by_xpath("//[@id='DataTables_Table_0']/tbody/tr")
for x in lines:
Date = driver.find_elements_by_class_name("Date")
record.acell(getNextRow(), Date[x].text)
# The error is here ^^^
Country = driver.find_element_by_class_name("Country")
record.acell(getNextRow(), Country[x].text)
League = driver.find_element_by_class_name("Region")
record.acell(getNextRow(), League[x].text)
HomeT = driver.find_elements_by_class_name("CompanyY")
record.acell(getNextRow(), HomeT[x].text)
VisitT = driver.find_element_by_class_name("CompanyV")
record.acell(getNextRow(), Visit[x].text)
这给了我这个错误消息:TypeError:列表索引必须是整数或切片,而不是 WebElement
如何在每个 tr 中执行循环并提取 td 信息?
我需要一些帮助。
编辑 在“for”语句中,使用 range(len(lines)) 而不是lines确实循环可以正常工作。
最佳答案
获得所有行后:
rows = driver.find_elements_by_xpath("//[@id='DataTables_Table_0']/tbody/tr")
...只需迭代它们并找到它们包含的 td:
for row in rows:
elem = row.find_element_by_tag_name('td')
print(elem.text)
关于Python Selenium : TypeError: list indices must be integers or slices, 不是 WebElement,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54408804/