如何解决TypeError:类型' WebElement'的对象Python Selenium中没有len()

时间:2018-03-29 10:12:19

标签: python list selenium selenium-webdriver webdriver

我想打印所有类似的元素,但一直出错(我使用的是 Pycharm )。

错误:

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

此行是引发错误的行: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()




2 个答案:

答案 0 :(得分:1)

您正在使用WebElement查找并返回与选择器匹配的第一个find_elements_by_xpath。您需要使用 protected synchronized void buildGoogleApiClient() { System.out.println("buildGoogleApiClient"); mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } 返回所有匹配元素

答案 1 :(得分:0)

错误说明了一切:

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

productname driver.find_element_by_xpath("//div[@class='product-title']")分配了返回类型,这是 WebElement WebElement 没有方法{{1 }}。可以在len()上调用len()

解决方案

当您尝试访问List项时,如:

List

产品名称旧价格折扣销售价格需要为print(productname[i].text + " : " + oldprice[i].text + " : " + discount[i].text + " : " + saleprice[i].text) 类型。

但您的代码读作:

List

产品名称 WebElement 旧价格折扣销售价格文本。因此,您需要将其更改为 WebElements 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 ,如下所示:

List