ChanGan
ChanGan

Reputation: 4318

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

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>

Upvotes: 30

Views: 176062

Answers (7)

mkumar0304
mkumar0304

Reputation: 697

    You can achieve this by using cssSelector 
    // Use of List web elements:
    String cssSelectorOfLoginButton="input[type='button'][id='login']"; 
    //****Add cssSelector of your 1st webelement
    //List<WebElement> button 
    =driver.findElements(By.cssSelector(cssSelectorOfLoginButton));
    button.get(0).click();

    I hope this work for you

Upvotes: 0

Misha Akovantsev
Misha Akovantsev

Reputation: 1825

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)

Upvotes: 23

user1710861
user1710861

Reputation: 423

use the text and value attributes instead of the id

driver.findElementByXpath("//input[@value='cancel'][@title='cancel']").click();

similarly for Next.

Upvotes: 5

Ripon Al Wasim
Ripon Al Wasim

Reputation: 37816

For Next button you can use xpath or cssSelector as below:

xpath for Next button: //input[@value='Next']

cssPath for Next button: input[value=Next]

Upvotes: 2

faramka
faramka

Reputation: 2234

In Selenium IDE you can do:

Command   |   clickAndWait
Target    |   //input[@value='Next' and @title='next']

It should work fine.

Upvotes: 20

Rohit Ware
Rohit Ware

Reputation: 2002

You can use xpath for for identifying that element.

Upvotes: 0

faramka
faramka

Reputation: 2234

You don't need to use only identifier as elements locators. You can use a few ways to find an element. Read this article and choose the best for you.

Upvotes: 1

Related Questions