python - 如何在 Python 中使用 Selenium 获取 <ol> 中 <li> 元素的长度?

标签 python selenium selenium-webdriver

我有一个 <ol>像下面这样在我的 HTML 中列出:

<ol id="search-results">
  <li class="foo">-</li>
  <li class="foo">-</li>
  <li class="foo">-</li>
  <li class="foo">-</li>
</ol>

我需要做的是验证 <ol>列表包含 <li>内的项目,即。搜索查询会得出实际结果。我目前的代码如下:

search_field = driver.find_element(By.NAME, 'query')
search_field.send_keys('Foo')
search_field.submit()

results_list = driver.find_element(By.ID, 'search-results')
assert len(results_list) > 0

但我得到了 TypeError: object of type 'FirefoxWebElement' has no len()运行时出错。

有什么办法可以克服吗?

最佳答案

你的

driver.find_element(By.ID, 'search-results')

不返回一个列表,而是一个元素。如果您想要包含所有 li 的列表,您可以使用 find_elements_by_xpath

尝试:

results_list = driver.find_elements_by_xpath("//ol[@id='search-results']/li[@class='foo']")
print(len(results_list))
assert len(results_list) > 0

关于python - 如何在 Python 中使用 Selenium 获取 <ol> 中 <li> 元素的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47038152/

相关文章:

Python & Selenium 点击和 "TypeError: string indices must be integers"

python - 如何在 Firefox 或 Chrome 中使用 Selenium webdriver 更改屏幕截图的目标目录

python - 如何将 pd.read_table 与 StringIO 文件对象一起使用?

python - 在 div 类中查找值

python - 如何使用 python 将参数传递给 bit.ly api?

java - Selenium : How to know current frame number or value?

python - 在python中以表格格式打印列表

python - 如何同时运行多个 Selenium Firefox 浏览器?

Selenium 在 WebElement 中获取 WebElement

c# - WebDriver - 元素不可点击 Chrome