如何解决TypeError:类型为'WebElement'的对象在Python Selenium中没有len() [英] How to resolve TypeError: object of type 'WebElement' has no len() in Python Selenium

查看:538
本文介绍了如何解决TypeError:类型为'WebElement'的对象在Python Selenium中没有len()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打印所有相似的元素,但是会不断出现错误(我正在使用 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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆