Skip to content Skip to sidebar Skip to footer

How To Resolve TypeError: Object Of Type 'WebElement' Has No Len() In Python Selenium

I want to print all similar elements but keep getting an error (I am using Pycharm). Error: TypeError: object of type 'WebElement' has no len() This line is the one throwing the e

Solution 1:

You are using find_element_by_xpath which find and returns the first WebElement matching the selector. You need to use find_elements_by_xpath which returns all the matching elements


Solution 2:

The error says it all :

num_page_items = len(productname) 
TypeError: object of type 'WebElement' has no len()

productname is assigned the return type from driver.find_element_by_xpath("//div[@class='product-title']"), which is a WebElement and WebElement have no method as len(). len() can be invoked on a List.

Solution

As you are trying to access List items as in :

print(productname[i].text + " : " + oldprice[i].text + " : " + discount[i].text + " : " + saleprice[i].text)

So productname, oldprice, discount and saleprice needs to be of List type.

But your code reads as :

productname = driver.find_element_by_xpath("//div[@class='product-title']")
oldprice = driver.find_element_by_css_selector("span.old-price-text").text
discount = driver.find_element_by_css_selector("div.discount > span").text
saleprice = driver.find_element_by_css_selector("span.new-price-text").text 

Where productname is a WebElement and oldprice, discount, and saleprice are text. So you need to change them as a List of WebElements as follows :

productname = driver.find_elements_by_xpath("//div[@class='product-title']")
oldprice = driver.find_elements_by_css_selector("span.old-price-text")
discount = driver.find_elements_by_css_selector("div.discount > span")
saleprice = driver.find_elements_by_css_selector("span.new-price-text")

Post a Comment for "How To Resolve TypeError: Object Of Type 'WebElement' Has No Len() In Python Selenium"