我想打印所有类似的元素,但一直出错(我使用的是 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()

答案 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