问题
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