问题描述
我想打印所有相似的元素,但是会不断出现错误(我正在使用 Pycharm ).
I want to print all similar elements but keep getting an error (I am using Pycharm).
错误:
TypeError: object of type 'WebElement' has no len()
此行是引发错误的行:num_page_items = len(productname)
This line is the one throwing the error: num_page_items = len(productname)
完整的硒代码:
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()
推荐答案
错误说明了一切:
num_page_items = len(productname)
TypeError: object of type 'WebElement' has no len()
为
产品名称分配了driver.find_element_by_xpath("//div[@class='product-title']")
的返回类型,这是 WebElement 和 WebElement 都没有方法作为len()
.可以在List
上调用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
.
在尝试访问List
项时,如:
print(productname[i].text + " : " + oldprice[i].text + " : " + discount[i].text + " : " + saleprice[i].text)
因此,产品名称,旧价格,折扣和销售价格必须为List
类型.
So productname, oldprice, discount and saleprice needs to be of List
type.
但是您的代码显示为:
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
其中产品名称是 WebElement 和旧价格,折扣和促销价格是文本.因此,您需要将它们更改为 WebElements 的List
,如下所示:
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")
这篇关于如何解决TypeError:类型为'WebElement'的对象在Python Selenium中没有len()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!