我是Java和Selenium的新手,所以如果我的问题听起来有点主要,请事先道歉。
我用:
driverChrome.findElements(By.className("blabla"));
查找以“blabla”作为其className的元素,例如:
<span class="blabla" title="the title">...</span>
现在,如果我想按其他属性查找所有元素怎么办?就像是:
driverChrome.findElements(By.titleValue("the title"));
这是我当前用于执行此任务的代码:
List<WebElement> spans = driverChrome.findElements(By.tagName("span"));
for (WebElement we : spans) {
if (we.getAttribute("title") != null) {
if (we.getAttribute("title").equals("the title")) {
...
break;
}
}
}
但是它不方便快捷。
最佳答案
通过归档元素时,有很多方法
1条绝对路径
<html>
<body>
<div>
<form>
<input id="demo"/>
</form>
</div>
</body>
<html>
获取“输入”标签
xpath="/html/body/div/form/input"
2相对路径
<html>
<body>
<div>
<form>
<input id="demo"/>
</form>
</div>
</body>
<html>
获取“输入”标签
xpath="//input"
3指数
<html>
<body>
<div>
<form>
<input id="demo1"/>
<input id="demo2">
</form>
</div>
</body>
<html>
获取输入“demo2”
xpath =“// input [1]”
4任意单一属性
<html>
<body>
<div>
<form>
<input id="demo1"/>
<input id="demo2" foo="bar">
</form>
</div>
</body>
<html>
获取输入“demo2”
xpath="//input[@id='demo2']" (equivalent to By.id)
要么
xpath="//input[@foo='bar']"
5任意多个属性
<html>
<body>
<div>
<form>
<input id="1" type="submit" />
<input id="2" foo="bar"/>
<input id="3" type="submit" foo="bar"/>
</form>
</div>
</body>
<html>
获取第三个输入
xpath="//input[@type='submit'][@foo='bar']"
要么
xpath="//input[@type='submit' and @foo='bar']"
如果使用xpath =“// input [@ type ='submit'或@ foo ='bar']”,则将得到一个数组。您可以通过driver.findElements(By.xpath(xpath))(java)获取列表。否则,您将获得第一个元素(如果仅使用driver.findElement)。因为所有这三个输入元素都满足您的条件“或”,所以它给了您第一个输入元素。
6个包含属性
<html>
<body>
<div>
<form>
<input id="1" type="submit" />
<input id="2" foo="bar" daddy="dog"/>
<input id="3" type="submit" foo="bar"/>
</form>
</div>
</body>
<html>
获取第二个输入
xpath="//input[@daddy]"
因为只有第二个属性的属性为“爸爸”
7内部搜寻
<html>
<body>
<div>
<form>
<input id="input1" daddy="dog" />
<input id="input2" daddy="pig"/>
</form>
</div>
<div>
<form>
<input id="input3" daddy="dog" />
<input id="input4" daddy="apple"/>
</form>
</div>
</body>
<html>
获得第二个div
xpath="//div[.//input[@daddy='dog'] and .//input[@daddy='apple']]"
总体而言,这些都是我现在可以解决的。希望能帮助到你。