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 error: num_page_items = len(productname)
Full selenium code:
from selenium import webdriver driver = webdriver.Chrome('/Users/reezalaq/PycharmProjects/untitled2/venv/driver/chromedriver') driver.get("https://www.blibli.com/jual/batik-pria?s=batik+pria") 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 num_page_items = len(productname) for i in range(num_page_items): print(productname[i].text + " : " + oldprice[i].text + " : " + discount[i].text + " : " + saleprice[i].text) driver.close()
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
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
.
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.