How to press/click the button using Selenium if the button does not have the Id?

ChanGan picture ChanGan · Jan 15, 2012 · Viewed 154.4k times · Source

I have 2 buttons Cancel and Next button on the same page but it has only one id (see the below code). I wanted to press Next but every time it is identifying the cancel button only not Next button. How to resolve this issue?

<td align="center">
     <input type="button" id="cancelButton" value="Cancel" title="cancel" class="Submit_Button" style="background-color: rgb(0, 0, 160);">
     <input type="submit" value="Next" title="next" class="Submit_Button">
</td>

Answer

Misha Akovantsev picture Misha Akovantsev · Jan 16, 2012

Use xpath selector (here's quick tutorial) instead of id:

#python:
from selenium.webdriver import Firefox

YOUR_PAGE_URL = 'http://mypage.com/'
NEXT_BUTTON_XPATH = '//input[@type="submit" and @title="next"]'

browser = Firefox()
browser.get(YOUR_PAGE_URL)

button = browser.find_element_by_xpath(NEXT_BUTTON_XPATH)
button.click()

Or, if you use "vanilla" Selenium, just use same xpath selector instead of button id:

NEXT_BUTTON_XPATH = '//input[@type="submit" and @title="next"]'
selenium.click(NEXT_BUTTON_XPATH)