Java 如何使用 webdriver 查找按钮元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27529967/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find button element with webdriver?
提问by kirk douglas
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?
有两个按钮是确认,另一个是取消我可以找到带有 XPath 的按钮,但我不想使用 XPath。在这种情况下,还有另一种方法可以找到按钮元素吗?
I tried this:
我试过这个:
driver.findElement(By.className("btn dialog-confirm btn-primary")).click();
It did not find the button Thank you for your help
它没有找到按钮 谢谢你的帮助
采纳答案by alecxe
Just check for a single dialog-confirm
class:
只需检查一个dialog-confirm
类:
driver.findElement(By.className("dialog-confirm")).click();
Or, use a CSS Selector
:
或者,使用一个CSS Selector
:
driver.findElement(By.cssSelector("button.dialog-confirm")).click()
回答by Master Slave
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
投票给 alecxe,你的尝试在两个帐户上是错误的,当匹配多个类时应该使用By.cssSelector
,并且当它们设置在同一个元素上时,你用一个点连接它们,比如
driver.findElement(By.cssSelector(".btn.dialog-confirm.btn-primary")).click();
回答by Harish Ekambaram
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.
添加到 alecxe 和主从的答案中。如果按按钮文字点击会更具体,也更容易理解。使用下面的 xpath 查找按钮单击的代码段。
driver.findElement(By.xpath("//button[text()='Confirm']")).click();
driver.findElement(By.xpath("//button[text()='Cancel']")).click();
回答by optimistic_creeper
Other ways using cssSelector:
使用 cssSelector 的其他方法:
Use full attribute i.e.:
driver.findElement(By.cssSelector("button[class='btn dialog-confirm btn-primary']"))
Use part of attribute i.e.:
driver.findElement(By.cssSelector("button[class*='dialog-confirm']"))
使用完整属性,即:
driver.findElement(By.cssSelector("button[class='btn dialog-confirm btn-primary']"))
使用属性的一部分,即:
driver.findElement(By.cssSelector("button[class*='dialog-confirm']"))
回答by Jaxx0rr
this worked for me:
这对我有用:
driver.find_element_by_class_name('buyable-full-width').click();