Home > Enterprise >  Python Selenium "TypeError: 'WebElement' object is not iterable"
Python Selenium "TypeError: 'WebElement' object is not iterable"

Time:10-22

I need help with my code. I use Selenium with python

elems = driver.find_element_by_xpath("//article[@class='page-container']/section/div[3]") 

for job in elems:
  
   job_list.append(job.get_attribute('href')) 

print(job_list)
The error is "TypeError: 'WebElement' object is not iterable".

I know that the result of elems is a WebElement, but I need to use find_element_by_xpath because I want a specific div and this div has not an unique id. I didn't find a way to convert WebElement in (for example) a string. Do you have any idea of an another way to have this specific div but not using find_element_by_xpath? Do you have any other idea to skirt the problem ?

CodePudding user response:

for job in elems:

If you pay attention, the compiler will think elems is a list.

But you've defined elems as

elems = driver.find_element_by_xpath("//article[@class='page-container']/section/div[3]") 

which will return a WebElement not list of WebElement.

Issue Explanation :

Note that find_element_by_xpath returns a web element where as find_elements_by_xpath returns a list.

Fix : (use find_elements not find_element)

elems = driver.find_elements_by_xpath("//article[@class='page-container']/section/div[3]") 

for job in elems:
    job_list.append(job.get_attribute('href')) 
print(job_list)
  • Related