How to locate the grandparent of elements using Selenium (Python) in a loop

347 Views Asked by At

I am trying to append the name of a value which it's child element is less then 120.

My code is

list = []
rate = driver.find_elements(By.XPATH, '//span[@class="sFive"]')
for e in rate:
    if int(e.text) < 120:
        title=e.find_element(By.XPATH, x).text #find ancestor element
        list.append(title)

print(list)

The x is where I need to find the grandparent which is the 21st span element up that branch.

The span element is

<span data-slnm="Brand" class="ng-star-inserted">Inter</span>
1

There are 1 best solutions below

3
undetected Selenium On

The target element being:

<span data-slnm="Brand" class="ng-star-inserted">Inter</span>

To locate the element which is the 21st grandparent <span> element up that branch you can use the either of the following locator strategies:

  • Identifying the 21st <span> ancestor:

    list = []
    rate = driver.find_elements(By.XPATH, '//span[@class="sFive"]')
    for e in rate:
        if int(e.text) < 120:
        title = e.find_element(By.XPATH, '//span[@class="sFive"]//ancestor::span[21]').text
        list.append(title)
    print(list)
    
  • Identifying the specific <span> ancestor:

    list = []
    rate = driver.find_elements(By.XPATH, '//span[@class="sFive"]')
    for e in rate:
        if int(e.text) < 120:
        title = e.find_element(By.XPATH, '//span[@class="sFive"]//ancestor::span[@class="ng-star-inserted" and @data-slnm="Brand"]').text
        list.append(title)
    print(list)