mardi 21 septembre 2021

How to print preceding siblings in xpath

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.

Aucun commentaire:

Enregistrer un commentaire