8

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

Kindle Q
  • 944
  • 2
  • 19
  • 28
kirk douglas
  • 577
  • 5
  • 18
  • 35

5 Answers5

14

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()
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • I get 'WebDriver' object has no attribute 'findElement' – Jaxx0rr Feb 14 '20 at 08:36
  • @Jaxx0rr Make sure everything is within scope, I noticed just having my try in the wrong place made it not work even though it seemed fine. Also double check to seee if you didn't miss any of the necessary imports at the top of the file – Gilder Aug 28 '22 at 18:11
8

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();
  • Great addition - although OP didn't want to use XPATH, many people finding this question probably will need to, because many websites do not use descriptive (or even any) classes. – kevlarr Mar 12 '18 at 18:15
6

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']"))
    
Community
  • 1
  • 1
optimistic_creeper
  • 2,739
  • 3
  • 23
  • 37
2

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();
Master Slave
  • 27,771
  • 4
  • 57
  • 55
0

this worked for me:

driver.find_element_by_class_name('buyable-full-width').click();
Jaxx0rr
  • 507
  • 4
  • 7