Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'WebElement' object is not iterable error

I am trying to extract all the links from wikipedia homepage but this code showing 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()  
like image 752
priyanshu goyal Avatar asked Sep 15 '16 21:09

priyanshu goyal


People also ask

How do I fix Typeerror WebElement object is not iterable?

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. Show activity on this post. Below code worked for me.

What are the WebElement in selenium?

What is a Selenium WebElement? A WebElement, in this case, a Selenium WebElement is essentially an HTML element on a website. HTML documents consist of HTML elements. Each HTML element consists of a start tag and an end tag.


2 Answers

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.

Solution: replace find_element_by_xpath with find_elements_by_xpath

Reference: selenium-python docs

like image 64
pr0gramist Avatar answered Oct 08 '22 09:10

pr0gramist


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')
like image 27
Hari Avatar answered Oct 08 '22 09:10

Hari