Python Basics

How to select li element in selenium python?

In certain cases we may want to fetch data from list by using Selenium in Python. The simplest solution to target any element by its tag name is to use find_element_by_tag_name.

Note: Selenium Python has similar function find_elements_by_tag_name. Do not use this one. It returns a list of targeted element.

Select li element in selenium python

If you want to fetch only list elements and if the webpage has only one list. Then targeting li is best solution. Now the webpage must have more than one li element. So instead of find_element_by_tag_name use find_elements_by_tag_name

Here it will return list of elements. So to fetch data we must have to loop through.

from selenium import webdriver

driver=webdriver.Chrome(“D:\\PythonProjects\\SeleniumTutorial\\chromedriver.exe”)

driver.get(“https://gyanol.com/selenium-tutorial-example”)

listelements=driver.find_elements_by_tag_name(‘li’)

for listelem in listelements:

print(listelem.text)

Output:

PHP

Python

Javascript

Jquery

Ajax

C#

Note: by calling .text on listelem it returned text with out html code.