[Solved] 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()  

Solution #1:

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

Respondent: pr0gramist

Solution #2:

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')
Respondent: Hari

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.