Python TypeError: 'WebElement' 对象不是可迭代的错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39520426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: 'WebElement' object is not iterable error
提问by priyanshu goyal
I am trying to extract all the links from wikipedia homepage but this code showing TypeError: 'WebElement' object is not iterable error.
我试图从维基百科主页中提取所有链接,但此代码显示 TypeError: 'WebElement' object is not iterable error。
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()
回答by pr0gramist
The problem is that you are using find_element_by_xpath
which return only one WebElement (which is not iterable), the find_elements_by_xpath
return a list of WebElements.
问题是您正在使用find_element_by_xpath
which 只返回一个 WebElement (不可迭代),find_elements_by_xpath
返回一个 WebElements 列表。
Solution: replace find_element_by_xpath
with find_elements_by_xpath
解决方法:替换find_element_by_xpath
为find_elements_by_xpath
回答by Hari
Below code worked for me.
下面的代码对我有用。
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')