Java 使用多个条件在 Selenium 中查找 WebElement
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30403415/
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
Using multiple criteria to find a WebElement in Selenium
提问by
I am using Selenium to test a website, does this work if I find and element by more than one criteria? for example :
我正在使用 Selenium 来测试一个网站,如果我通过多个标准查找和元素,这是否有效?例如 :
driverChrome.findElements(By.tagName("input").id("id_Start"));
or
或者
driverChrome.findElements(By.tagName("input").id("id_Start").className("blabla"));
采纳答案by Saifur
No it does not. You cannot concatenate/add selectors like that. This is not valid anyway. However, you can write the selectors such a way that will cover all the scenarios and use that with findElements()
不,不是的。您不能像这样连接/添加选择器。这无论如何都无效。但是,您可以编写覆盖所有场景的选择器并将其用于findElements()
By byXpath = By.xpath("//input[(@id='id_Start') and (@class = 'blabla')]")
List<WebElement> elements = driver.findElements(byXpath);
This should return you a list of elements with input
tags having class name blabla
and having id
id_Start
这应该返回一个元素列表,其中包含input
具有类名blabla
和标签的元素id
id_Start
回答by Robbie Wareham
CSS Selectors would be perfect in this scenario.
在这种情况下,CSS 选择器将是完美的。
Your example would
你的例子会
By.css("input#id_start.blabla")
There are lots of information if you search for CSS selectors. Also, when dealing with classes, CSS is easier than XPath because Xpath treats class as a literal string, where as CSS treats it as a space delimited collection
如果您搜索 CSS 选择器,将会有很多信息。此外,在处理类时,CSS 比 XPath 更容易,因为 Xpath 将类视为文字字符串,而 CSS 将其视为以空格分隔的集合
回答by George
To combine By statements, use ByChained:
要组合 By 语句,请使用 ByChained:
driverChrome.findElements(
new ByChained(
By.tagName("input"),
By.id("id_Start"),
By.className("blabla")
)
)
However if the criteria refer to the same element, see @Saifur's answer.
但是,如果标准涉及相同的元素,请参阅@Saifur 的回答。