0

In my app, I can expect one of two elements (a or b) to appear. I currently have: el1 = driver.find_element_by_id("a")

But, I'd like to do something like: el1 = driver.find_element_by_id("a" or "b")

Is that possible in selenium? I'm doing this in Python, if that helps.

3 Answers 3

1

Simple and straightforward solution:

try:
    # Look for first element
    el1 = driver.find_element_by_id('a')
except selenium.common.exceptions.NoSuchElementException:
    # Look for the second if the first does not exist
    el1 = driver.find_element_by_id('b')
Sign up to request clarification or add additional context in comments.

Comments

1

you can use xpath in that case :

el1 = driver.find_element_by_xpath("//*[@id= 'a' or @id = 'b']")

I am assuming that two tags in HTML has two different ids, you can write or condition in xpath like above.

Update :

Heads up to anyone implementing this with an android app, the syntax is:

el1 = driver.find_element_by_xpath("/hierarchy/a" or "/hierarchy/b")

5 Comments

I'm testing an android app so the xpath looks more like "/hierarchy/a". Will try to do what you suggested with my xpath.
It worked. Heads up to anyone implementing this with an android app, the syntax is: el1 = driver.find_element_by_xpath("/hierarchy/a" or "/hierarchy/b")
I have updated for android as well. Meanwhile, Was it helpful ?if yes, can you accept this answer so that it will be available in green color for future readers. In case if you would like to accept this answer, please feel free click on check mark which is right aside with voting buttons. I'd appreciate your time and response on this.
I spoke too soon, el1 = driver.find_element_by_xpath("/hierarchy/a" or "/hierarchy/b") only worked when the provided element is a. Also, would something like this work for id instead of xpath? Or is selenium picky?
no it won't work for id, id does not have support for AND or OR, you may be able to do it with css selector.
0

In pure Python you can do this:

el1 = driver.find_element_by_id("a") if driver.find_element_by_id("a") else driver.find_element_by_id("b") if driver.find_element_by_id("b") else None

1 Comment

if a or b is not available in DOM, OP is gonna get NoSuchElement exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.