How to get the length of the <li> elements in an <ol> with Selenium in Python?

你离开我真会死。 提交于 2021-01-27 20:22:40

问题


I have an <ol> list in my HTML like the following:

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

What I need to do is to verify that the <ol> list contains <li> items within, ie. a search query comes up with actual results. My current code is as follows:

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

but I get the TypeError: object of type 'FirefoxWebElement' has no len() error when I run that.

Any ideas how to overcome that?


回答1:


Your

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

don't return a list but an element. If you want the list with all the li, you could use the find_elements_by_xpath.

Try with:

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



回答2:


Try the following:

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

results_list = driver.find_elements(By.CSS_SELECTOR, '#search-results > li')
assert len(results_list) > 0


来源:https://stackoverflow.com/questions/47038152/how-to-get-the-length-of-the-li-elements-in-an-ol-with-selenium-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!