TypeError: 'WebElement' object is not iterable error

TypeError: 'WebElement' object is not iterable error

我正在尝试从维基百科主页提取所有链接,但此代码显示 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 其中 return 只有一个 WebElement(不可迭代),find_elements_by_xpath return WebElement 列表。

解决方法:将find_element_by_xpath替换为find_elements_by_xpath

Reference: selenium-python docs

下面的代码对我有用。

from selenium import webdriver
driver=webdriver.Firefox()
driver.get("https://www.google.co.in/")
list_links=driver.find_elements_by_tag_name('a')

for i in list_links:
    print i.get_attribute('href')