2

The key HTML is:

<div class="col col3 actionCol"> 
  <button type="submit" class="booking fRight">Book</button>
</div>

but we also have other forms on the same page, e.g. for login, that have a similar "submit" button.

How do i click this specific one?

2

I would recommend you find the element using xpath and specify index within xpath. So for the button you are referring to, the code with indexed xpath would be

driver.findElement(By.xpath("(//button[contains(text(),'Book')])[2]"));

Alternatively, if you wish to avoid indexes, you may write a more specific xpath to find the element

driver.findElement(By.xpath("//div[@class='row roundTripHead' and not(contains(@style,'display: none'))]//button"));

The above xpath will discard element which has style attribute with value display:none

  • This is both hard to read and brittle. the not contains @style 'display: none isn't good for future changes. It's a valid answer though for those wishing to use xpath and this approach. – Michael Durrant Nov 25 '16 at 14:47
  • Hi Michael, i was able to use the java script executor and click on the link...awesome..thanks – praneeth kothari Nov 25 '16 at 18:36
3

You can find both of them into an array and find which one you want by using array indexing.

buttonArray = webdriver.findElements(submit button xpath / css selector)
firstButton = buttonArray[0]
secondButton = buttonArray[1]
1

Be specific enough (but no more) to uniquely select 1 element

Generally look to css selectors first, for greatest readability.

Try using button[type='submit'] for your selector and click on it, e.g.

findElement("button[type='submit']").click

if that is not specific enough, scope it to the button or form class, examples:

button.booking[type='submit']
form button.booking[type='submit']
form.booking button[type='submit']
# Allow form to be put anywhere on the page and other forms to exist

If that is not specific enough (the page has two forms with the same name...) you can scope it to the specific occurrence, e.g. for the first occurrence use:

form.booking button.booking[type='submit'][0]`  
# However this is now tied to page layout if form order is changed

"but no more" in the title generally means don't hard-code a selector using the surrounding page layout. It may be unique but it then becomes tied the the page layout and breaks if the layout changes.

0

Please use the index to find the particular element.

driver.findElement(By.xpath("(//*[text()='Book'])[1]"));

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.