如何使用webdriver查找按钮元素?

kir*_*las 5 java selenium selenium-webdriver

我有一个按钮的以下代码:

<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>
Run Code Online (Sandbox Code Playgroud)

有两个按钮是确认,另一个是取消我可以找到XPath按钮,但我不想使用XPath.在这种情况下是否有其他方法可以找到按钮元素?

我试过这个:

driver.findElement(By.className("btn dialog-confirm btn-primary")).click();
Run Code Online (Sandbox Code Playgroud)

它没有找到按钮谢谢你的帮助

ale*_*cxe 6

只需检查一个dialog-confirm班级:

driver.findElement(By.className("dialog-confirm")).click();
Run Code Online (Sandbox Code Playgroud)

或者,使用CSS Selector:

driver.findElement(By.cssSelector("button.dialog-confirm")).click()
Run Code Online (Sandbox Code Playgroud)


小智 6

添加到 alecxe 和主从的答案中。如果按按钮文字点击会更具体,也更容易理解。使用下面的 xpath 查找按钮单击的代码段。

driver.findElement(By.xpath("//button[text()='Confirm']")).click();
driver.findElement(By.xpath("//button[text()='Cancel']")).click();
Run Code Online (Sandbox Code Playgroud)


opt*_*per 5

使用cssSelector的其他方式:

  1. 使用完整属性,即:

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

  2. 使用部分属性,即:

    driver.findElement(By.cssSelector("button[class*='dialog-confirm']"))
    
    Run Code Online (Sandbox Code Playgroud)