Hugo Aroeira
Hugo Aroeira

Reputation: 33

Is there a way to put find_element_by_xpath inside for loop?

I am using python with selenium to try to iterate over a loop.

Here is my code:

rowsArray = driver.find_elements_by_class_name("search-results__result-item")
countRows = (len(rowsArray))

This way I fint countRows = 25 and then I try to iterate in a for loop:

for i in range(countRows):
   row = driver.find_elements_by_class_name("search-results__result-item")[i]
   print(row)

This way it works well, but since I need to get elements inside the element that has the 'search-results__result-item' class, I tried to change it using xpath inside the loop:

row = driver.find_element_by_xpath(".//li[contains(@class, 'search-results__result-item')][" + str(i) + "]"

or

row = driver.find_element_by_xpath("//li[@class='search-results__result-item']" + str(i) + "]")

But all I get is the message:

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //li[@class='search-results__result-item'][0]

What is the right way to iterate over a loop using XPath?

Upvotes: 1

Views: 201

Answers (2)

cruisepandey
cruisepandey

Reputation: 29362

//li[@class='search-results__result-item'][0]

the clue is here [0] does not represent any node it should start from [1]

or use the below code:

j = 1
for i in range(len(driver.find_elements_by_class_name("search-results__result-item"))):
    row = driver.find_element_by_xpath(f"(.//li[contains(@class, 'search-results__result-item')])[{j}]")
    print(row.text)
    j = j + 1

Upvotes: 1

KunduK
KunduK

Reputation: 33384

If I understood your problem correctly, then yes it is possible.if you need to access child element under the same parent each time you can use the following two options.

Option 1:

rowsArray = driver.find_elements_by_class_name("search-results__result-item")
countRows = (len(rowsArray))

for i in range(countRows):
    childelement=rowsArray[i].find_element_by_xpath(".//li[contains(@class, 'search-results__result-item')]")

Option 2:

rowsArray = driver.find_elements_by_class_name("search-results__result-item")

for row in rowsArray:
   childelement=row.find_element_by_xpath(".//li[contains(@class, 'search-results__result-item')]")

Upvotes: 0

Related Questions