0

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>
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
Oris
  • 73
  • 8

1 Answers1

0

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)
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
  • Tried by identifying the specific ancestor, but it throw an error NoSuchElementException. Do I need maybe to locate the parent
    which is
    and then locate the ? Do you know how should I go about it? Also, why we need to add //span[@class="sFive"] again in the e.find_element if it was already found in the rate variable? Thanks!
    – Oris Aug 20 '22 at 10:54
  • Its my first time dealing with ancestors but I would add here that the is not a direct ancestor but there are many branches that descends from on main
    before splitting into different branches. Does this fact change anything?
    – Oris Aug 20 '22 at 11:06
  • Let's discuss the issue in [Selenium](https://chat.stackoverflow.com/rooms/223360/selenium) room. – undetected Selenium Aug 20 '22 at 11:40