Home > other >  Selenium Python Iterate over li elements inside ol
Selenium Python Iterate over li elements inside ol

Time:09-24

I need to extract, using python and selenium, the text of multiple li elements, all of them, inside an ol element. The list is like this:

/html/body/main/div/div/section/ol/li[3]/div/div/div[2]/div[1]/a[1]/h2
/html/body/main/div/div/section/ol/li[4]/div/div/div[2]/div[1]/a[1]/h2
/html/body/main/div/div/section/ol/li[5]/div/div/div[2]/div[1]/a[1]/h2
/html/body/main/div/div/section/ol/li[6]/div/div/div[2]/div[1]/a[1]/h2
...

So far, I'm using the following code, but this code shows only one element, and not the whole list. What is wrong with it? Thanks!

articles_list=r'/html/body/main/div/div/section/ol'
articles_elements = driver.find_elements_by_xpath(articles_list)

for article in articles_elements:
    title = article.find_element_by_xpath('.//div/div/div[2]/div[1]/a[1]/h2').text
    print('Title:' title)

CodePudding user response:

I see that li tag has increment indices like [3] then [4] and so on..

You can look for each and every web element by declaring i = 3, initially and then increment using programmatically.

a = 3
size_of_list  = driver.find_elements_by_xpath(f"/html/body/main/div/div/section/ol/li")
for i in range(size_of_list):
    title = driver.find_element_by_xpath(f"/html/body/main/div/div/section/ol/li[{a}]/div/div/div[2]/div[1]/a[1]/h2").text
    print('Title:', title)
    a = a  1
  • Related