Home > Enterprise >  How to print preceding siblings in xpath
How to print preceding siblings in xpath

Time:09-22

I'm trying to get the preceding siblings of an element using xpath.

There are 2 siblings that I'm looking for:

sibling_two = driver.find_elements_by_xpath("//span[contains(@class, 'tag')]/preceding-sibling::a[2]")
sibling_one = driver.find_elements_by_xpath("//span[contains(@class, 'tag')]/preceding-sibling::a[1]")

If sibling_two doesn't exist, I want to output sibling_one

This is my code, but it's only outputting sibling_two values

if sibling_two:
    for i in sibling_two:
        print(i.text)
else:
    for a in sibling_one:
         print(a.text)

Any ideas on how to fix this to output both sibling_one and sibling_two values?

Thank you for taking the time to read my question and help out.

CodePudding user response:

Don't use if else, use two ifs:

if sibling_two:
    for i in sibling_two:
        print(i.text)
if sibling_one:
    for a in sibling_one:
         print(a.text)

CodePudding user response:

You have used find_elements which will return a list in Python.

I'm not sure if you really want to use find_elements or find_element.

In case you want to use find_elements

try:
    if len(sibling_two) == 0:
        print("We want to output sibling_one")
        for i in sibling_one:
            print(i.text)
    else:
        print("Since sibling_two seems to have something in it, we would extract from the same.")
        for j in sibling_two:
            print(j.text)
except:
    print("Something went wrong")
    pass
  • Related