简体   繁体   中英

How to extract text inside a li tag using Selenium in Python

This is the HTML code from where I need to extract the text:

<li class="inline t-24 t-black t-normal break-words">
Nilesh Sengupta
</li>

This is my code:

items = driver.find_elements_by_tag_name("li")
print(items.text)

driver.find_elements_by_tag_name("li") returns a list of web elements
So in order to extract texts from all the elements you have to iterate on all the elements in the list and extract text from each one.
So you should

items = driver.find_elements_by_tag_name("li")
for el in items:
  print(el.text)

In case you want to extract a text from a specific element you should use find_element_by_tag_name instead of find_elements_by_tag_name .
In this case
item = driver.find_element_by_tag_name("li")
item is a web element and you can extract a text from it directly by print(item.text)

With css selectors is the best way:

tag_list = driver.find_elements_by_css_selector(".inline.t-24.t-black.t-normal.break-words").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