如何在硒的xpath中使用count()函数?
问题描述:
使用findElements()
和size()
方法我们可以得到计数。 但我想在xpath中使用count()函数提取计数。如何在硒的xpath中使用count()函数?
计数函数会返回一个整数值吗?
假设, 我的XPath是(//input[@id='stack'])[3]
,并有与//input[@name='hai']
3层匹配的节点,我可以修改我的XPath像下面?
(//input[@id='stack'])[count(//input[@name=''hai])]
答
是的,如果
count(//input[@name='hai'])
评估为
3
然后
(//input[@id='stack'])[count(//input[@name='hai'])]
会选择相同的节点作为
(//input[@id='stack'])[3]
会选择。
但是,你的意图是相当明确,尤其是考虑到
//input[@id='stack']
将选择所有 的'stack'
的id
属性值input
元素。通常id
属性值 在文档中是唯一的,所以通常这只会选择一个 单个元素。(//input[@id='stack'])[count(//input[@name='hai'])]
假定有id'ed为'stack
“因为有一个名为'hai'
input
元素至少多达input
元素 - 一个奇怪的假设。
答
driver.findElements()
返回WebElements的名单,并.size()
返回一个列表的整数大小,所以我觉得你们会有更好做了以下内容:
int myCount = driver.findElements(By.xpath("<Your Xpath Here>")).size();
这将让您元素的个数在您的网页上匹配您的xpath输入
嘿@kjhughes谢谢ton..its工作! – Toothless