Search code examples
pythonselenium-chromedriver

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

  • 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