whydoieven
whydoieven

Reputation: 599

Using an OR condition in Xpath to identify the same element

I have this logic which gets the current page's title first clicks on next button, fetches the title again and if both the titles are the same, meaning navigation has not moved to the next page, it clicks on Next again.

However, my problem is that the title element's Xpath differs - the same title element has two Xpaths. One is some pages the other in some other pages.

It is either this,

(.//span[@class='g-title'])[2]

OR

.//span[@class='g-title']

So, how can I handle this?

Upvotes: 18

Views: 120986

Answers (4)

Alex
Alex

Reputation: 187

I had an interesting insight I had using this method. In my python code I was clicking a cart button and the or "|" ONLY works with separate xpath statements like so ...

WebDriverWait(webdriver,20).until(EC.visibility_of_element_located((By.XPATH,"//*[@class='buttoncount-1'] | //button[contains(text(), 'Add to Cart')]")))

or

btn = webdriver.find_element_by_xpath("//*[@class='buttoncount-1'] | //button[contains(text(), 'Add to Cart')]")

I found that "or" ONLY works when they share the same bracket []

 WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//button[contains(text(), 'Add to Cart') or contains(text(),'Buy')]"))).click()

And since you're here. If you're curious about "and" statements this worked for me...

 WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//button[contains(text(), 'Continue To Order Rev')][@data-attr='continueToOrderReviewBtn']"))).click()

Simply pairing two separate statements was sufficient. No "and" necessary. Note: This was all in python. I do not know how this will transfer over to java. Hope this was somewhat useful. It took me a few migraines to narrow this down.

Upvotes: 4

manish dagur
manish dagur

Reputation: 121

You can use or, like below:

//tr[@class='alternateRow' or @class='itemRow']

Upvotes: 12

Prasad
Prasad

Reputation: 956

If the element has two xpath, then you can write two xpaths like below

xpath1 | xpath2

Eg: //input[@name="username"] | //input[@id="wm_login-username"]

It will choose any one xpath

Upvotes: 45

Ajinkya
Ajinkya

Reputation: 22710

You can use or operator like

(.//span[@class='g-title'])[2] or .//span[@class='g-title']

For more details : Two conditions using OR in XPATH

Upvotes: 7

Related Questions