Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find button element with webdriver?

I have the following code for a button :

<div class="buttons">
<button class="btn dialog-confirm btn-primary" style="margin-left: 4px;">Confirm</button>
<button class="btn dialog-cancel" style="margin-left: 4px;">Cancel</button>
</div>

There are two buttons on is Confirm and another is Cancel I can find the button with XPath but I don't want to use XPath. Is there another way to find the button element in this case?

I tried this:

driver.findElement(By.className("btn dialog-confirm btn-primary")).click();

It did not find the button Thank you for your help

like image 361
kirk douglas Avatar asked Dec 17 '14 16:12

kirk douglas


4 Answers

Just check for a single dialog-confirm class:

driver.findElement(By.className("dialog-confirm")).click();

Or, use a CSS Selector:

driver.findElement(By.cssSelector("button.dialog-confirm")).click()
like image 50
alecxe Avatar answered Oct 05 '22 16:10

alecxe


Added to alecxe and master slave's answer. It would be more specific if it is clicked by the button text, which is also easier to understand. Find the snippet for button click with xpath below.

driver.findElement(By.xpath("//button[text()='Confirm']")).click();
driver.findElement(By.xpath("//button[text()='Cancel']")).click();
like image 20
Harish Ekambaram Avatar answered Oct 05 '22 15:10

Harish Ekambaram


Other ways using cssSelector:

  1. Use full attribute i.e.:

    driver.findElement(By.cssSelector("button[class='btn dialog-confirm btn-primary']"))

  2. Use part of attribute i.e.:

     driver.findElement(By.cssSelector("button[class*='dialog-confirm']"))
    
like image 34
optimistic_creeper Avatar answered Oct 05 '22 17:10

optimistic_creeper


vote up for alecxe, your attempt was wrong on two accounts, when matching on multiple classes you should use By.cssSelector, and when they are set on the same element, you concatenate them with a dot, like

driver.findElement(By.cssSelector(".btn.dialog-confirm.btn-primary")).click();
like image 29
Master Slave Avatar answered Oct 05 '22 17:10

Master Slave