I have this issue with script: TypeError: 'FirefoxWebElement' object is not iterable
I have this issue with script: TypeError: 'FirefoxWebElement' object is not iterable
我在执行此脚本时遇到问题:
pic_hrefs = [elem.get_attribute('a href') for elem in hrefs]
Traceback (most recent call last):
File "IB.py", line 56, in <module>
kidCudix.like_photo('comfort')
File "IB.py", line 41, in like_photo
pic_hrefs = [elem.get_attribute('a href') for elem in hrefs]
TypeError: 'FirefoxWebElement' object is not iterable
首先,elem.get_attribute('a href')
是有问题的,因为 'a href'
不是一个有效的属性。相反,您想使用 elem.get_attribute('href')
。
但是,这不是您遇到的错误。
错误消息 (TypeError: 'FirefoxWebElement' object is not iterable
) 暗示您的输入可迭代对象 (hrefs
) 属于 FirefoxWebElement
类型,因为单个FirefoxWebElement
不可迭代。您需要在列表理解中使用 list 元素,而不是单个元素。 (列表理解从另一个输入可迭代创建一个列表)。你的理解应该是这样的:
hrefs = [elem.get_attribute('href') for elem in elements]
示例:
问题含糊不清,但您可能正试图在网页上创建链接列表。要获取所有链接的列表,一般模式是:
- 创建网络驱动程序
- 导航到页面
- 找到代表锚标签的所有元素
- 从每个元素中提取
href
属性并将它们存储在列表中
您可以使用如下代码来做到这一点:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://some_url')
elements = driver.find_elements_by_tag_name('a')
hrefs = [elem.get_attribute('href') for elem in elements]
请注意 find_elements_by_tag_name('a')
returns WebElement
的 list,我将在后续的列表理解中使用它。另请注意,使用的方法是 find_elements_by_tag_name
(复数)。这不同于 find_element_by_tag_name
(单数),它只会定位一个元素。
我在执行此脚本时遇到问题:
pic_hrefs = [elem.get_attribute('a href') for elem in hrefs]
Traceback (most recent call last):
File "IB.py", line 56, in <module>
kidCudix.like_photo('comfort')
File "IB.py", line 41, in like_photo
pic_hrefs = [elem.get_attribute('a href') for elem in hrefs]
TypeError: 'FirefoxWebElement' object is not iterable
首先,elem.get_attribute('a href')
是有问题的,因为 'a href'
不是一个有效的属性。相反,您想使用 elem.get_attribute('href')
。
但是,这不是您遇到的错误。
错误消息 (TypeError: 'FirefoxWebElement' object is not iterable
) 暗示您的输入可迭代对象 (hrefs
) 属于 FirefoxWebElement
类型,因为单个FirefoxWebElement
不可迭代。您需要在列表理解中使用 list 元素,而不是单个元素。 (列表理解从另一个输入可迭代创建一个列表)。你的理解应该是这样的:
hrefs = [elem.get_attribute('href') for elem in elements]
示例:
问题含糊不清,但您可能正试图在网页上创建链接列表。要获取所有链接的列表,一般模式是:
- 创建网络驱动程序
- 导航到页面
- 找到代表锚标签的所有元素
- 从每个元素中提取
href
属性并将它们存储在列表中
您可以使用如下代码来做到这一点:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://some_url')
elements = driver.find_elements_by_tag_name('a')
hrefs = [elem.get_attribute('href') for elem in elements]
请注意 find_elements_by_tag_name('a')
returns WebElement
的 list,我将在后续的列表理解中使用它。另请注意,使用的方法是 find_elements_by_tag_name
(复数)。这不同于 find_element_by_tag_name
(单数),它只会定位一个元素。