Python Selenium : TypeError: list indices must be integers or slices, 不是 WebElement

标签 python python-3.x selenium selenium-webdriver gspread

您好,我正在尝试对不同的元素 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/

相关文章:

java - 无法使用 Selenium(java) 从网站抓取错误消息并在 Eclipse 控制台中打印

java - 如何使用 Java Explicit WebDriver Wait 等待 Grid execution spinner

javascript - 尝试使用 Selenium 和 Python 通过使用框架和 Javascript 的网页登录时出现 ERR_TOO_MANY_REDIRECTS 错误

python - imp.load_source : 'module' has no attribute 'foo' 出现问题

python - 从 Python2 升级到 Python3 时的字符串/字节问题

python - 尝试使用 Python 3.7.2 和 IMAPClient 批量删除电子邮件 - imaplib.IMAP4.error : UID command error: BAD [b'Command line too large']

python - 在一行中打印文本文件中的文本

python - 如何使用字符串作为 csv 阅读器的输入而不将其存储到文件中

python - 我在运行一个简单的 pyttsx3 示例时遇到错误

python - REST API 的 url 缓存系统的最有效查找