首页 > 解决方案 > 执行以下脚本时遇到“TypeError:'WebElement' 类型的对象没有 len()”

问题描述

我正在尝试使用 assert equal 函数检查产品是否为 12。请检查我尝试过的以下脚本:

def test_search(self):
    driver=self.driver
    driver.get("http://magento-demo.lexiconn.com/")
    driver.maximize_window()
    driver.find_element_by_xpath(".//*[@id='search']").send_keys("Bed & Bath")
    driver.find_element_by_xpath(".//*[@id='search_mini_form']/div[1]/button").click()
    lis = driver.find_element_by_xpath("//h2[@class='product-name'] / a")
    self.assertEqual(12,len(lis))

标签: pythonseleniumselenium-webdriver

解决方案


替换这个:

lis = driver.find_element_by_xpath("//h2[@class='product-name']/a")  

至 :

lis = driver.find_elements_by_xpath("//h2[@class='product-name']/a")  

请注意,这find_elements将返回一个web 元素列表,如果找到, as将只返回一个元素。 find_element


推荐阅读