TypeError:“WebElement”对象不是可迭代错误

2024-05-06

我试图从维基百科主页提取所有链接,但此代码显示 TypeError: 'WebElement' object is not iterable 错误。

import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser=webdriver.Chrome()
browser.get('https://en.wikipedia.org/wiki/Main_Page')
search=[]
search=browser.find_element_by_xpath('//*[@href]')


for ii in search:
  print(ii.get_attribute('href'))

time.sleep(4)
browser.close()  

问题是你正在使用find_element_by_xpath只返回一个 WebElement(不可迭代),find_elements_by_xpath返回 WebElement 的列表。

解决方法:更换find_element_by_xpath with find_elements_by_xpath

参考:selenium-python 文档 https://selenium-python.readthedocs.io/locating-elements.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeError:“WebElement”对象不是可迭代错误 的相关文章

随机推荐