0

Please let me know xpath for below:

Shop Now

There are two buttons named as Shop now and I want to redirect to only 1 Shop now button. Both button will redirect to same URL. enter image description here

1
  • My question is - Why Xpath only? Why not CSS Locator? May 3 '18 at 15:31
1

Please find below the Xpath for the shop now button

For clicking the first shop now button

driver.findElementsByXPath("//a[contains(text(),'Shop Now')][1]");

For clicking the second shop now button

driver.findElementsByXPath("//a[contains(text(),'Shop Now')][2]");
0

Locate first button:

//a[@class='shop_now btn'][1]

or

//a[normalize-space()='Shop Now'][1]

Locate second button:

//a[@class='shop_now btn'][2]

or

//a[normalize-space()='Shop Now'][2]
0

To locate an element using xpath which have multiple matches means use "collections" concept.

driver.findElement(By.xpath(("//a[@class='shop_now btn']")[1]));

The above Xpath will locate the first "shop now" button.

You can also use "linkText" locator for locating the "Shop now" button.

driver.findElement(By.linkText("Shop Now"));
0

If the button that you would like to use is always within the div with class mattresscontent, I would use the css selector: "div.matresscontent a.shop_now"

This is in the assumption that the other show now button is not inside a div with class mattresscontent. In this way the button has a unique selector that is independent of other show now buttons on the page. I use mostly CSS selectors, with xpath you could do something similar.

What to me is important is to not say "take the first or the second button with the show_now class". If the other shop now button is removed or if a 3rd button is added, the behavior of your test would change. If you are for example using the 2nd button and the 1st button is removed from the page at some point, then your test will fail because there is no 2nd button anymore. This is undesired, as the button you intended to use is still there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.