【问题标题】:TypeError: 'WebElement' object is not iterableTypeError: \'WebElement\' 对象不可迭代
【发布时间】:2022-12-12 07:00:09
【问题描述】:
from selenium.webdriver.common.keys import Keys
import pandas as pd
from selenium.webdriver.common.by import By
from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.investing.com/crypto/currencies")
elem = driver.find_element(By.TAG_NAME,'table')

head = elem.find_element(By.TAG_NAME,'thead')
body = elem.find_element(By.TAG_NAME,'tbody')

list_rows = []

for items in body.find_element(By.TAG_NAME,'tr'):
    list_cells = []
    for item in items.find_element(By.TAG_NAME,'td'):
        list_cells.append(item.text)
    list_rows.append(list_cells)
driver.close()

输出对于 body.find_element(By.TAG_NAME,'tr') 中的项目: TypeError: 'WebElement' 对象不可迭代

我想用 selenium 和 pandas 从网站上抓取一张桌子。 但是我的 for 循环中出现了一些错误。 请任何专家解决这个问题。 请给我一个代码,我可以用它来从任何网页的表格中抓取数据。

我的错误是打击对于 body.find_element(By.TAG_NAME,'tr') 中的项目: TypeError: 'WebElement' 对象不可迭代

【问题讨论】:

  • find_element这个名字表明它只返回一个元素;错误似乎证实了这一点。可能有一个返回多个元素的变体。

标签: python selenium for-loop selenium-webdriver web-scraping


【解决方案1】:

find_element 返回单个 Web 元素对象,而您需要获取 Web 元素对象列表。 find_elements 这样做。
因此,您需要将表单 find_element 更改为 find_elements,这样它将是:

for items in body.find_elements(By.TAG_NAME,'tr'):
    list_cells = []
    for item in items.find_elements(By.TAG_NAME,'td'):
        list_cells.append(item.text)
    list_rows.append(list_cells)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-25
    • 2023-03-06
    • 2021-12-07
    • 1970-01-01
    • 2013-09-01
    • 2020-03-03
    • 1970-01-01
    • 2017-08-27
    相关资源
    最近更新 更多