简体   繁体   中英

get all <li> of <ul> selenium python3

I have an html like this:

<ul class="page">
   <li id="p1"></li>
   <li id="p2"></li>
   <li id="p3"></li>
</ul>

I tried to find all the < li >s under that < ul > with the following code using selenium Webdriver in python:

my_ul = driver.find_element_by_xpath("//ul[@class='page']")
all_li = my_ul.find_element_by_tag_name("li")
    for li in all_li:
        print(li.text)

but when I ru it I got an Error:

>       for li in all_li:
E       TypeError: 'WebElement' object is not iterable

can anybody explain to me what's wrong??

many thanks!

find_element_by_tag_name returns a single element, you need to fetch the list to iterate over it. For that you need to use find_elements_by_tag_name .
Your code should be like:

my_ul = driver.find_element_by_xpath("//ul[@class='page']")
all_li = my_ul.find_elements_by_tag_name("li")
    for li in all_li:
        print(li.text)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM