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

7

30

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>
Chervil answered 15/1, 2012 at 17:18 Comment(1)
What are you using? Selenium RC or WebDriver (Selenium 2)? Which language are you using? Java? C#? Python? or what?Inositol
D
20

In Selenium IDE you can do:

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

It should work fine.

Disposition answered 16/1, 2012 at 13:15 Comment(0)
P
23

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)
Phenomena answered 16/1, 2012 at 7:38 Comment(0)
D
20

In Selenium IDE you can do:

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

It should work fine.

Disposition answered 16/1, 2012 at 13:15 Comment(0)
S
5

use the text and value attributes instead of the id

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

similarly for Next.

Stellite answered 16/2, 2014 at 5:44 Comment(0)
I
2

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]

Inositol answered 16/1, 2013 at 4:52 Comment(0)
D
1

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.

Disposition answered 16/1, 2012 at 8:14 Comment(1)
But after reading you should know what to do, when the element has not got an 'id' attribute.Disposition
F
0

You can use xpath for for identifying that element.

Fitzsimmons answered 16/1, 2012 at 11:33 Comment(0)
D
0
    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
Dryad answered 1/6, 2018 at 12:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.