使用正则表达式通过 Xpath 查找 WebElement

Finding WebElement by Xpath Using Regex

我有以下 WebElements:

<input id="" type="checkbox" value="/p1/foobar1" name="checkbox1" partition="p1" onclick=""/>
<input id="" type="checkbox" value="/p1/foobar" name="checkbox2" partition="p1" onclick=""/>
<input id="" type="checkbox" value="/p2/foobar2" name="checkbox3" partition="p2" onclick=""/>

我想在 xpath 中使用正则表达式根据值属性在上面的源代码中找到第二个元素(值为 /p1/foobar 的元素)。我尝试了以下方法:

driver.findElement(By.xpath("//input[matches(@value,'.*\/foobar$')]"));

但它抛出 InvalidSelectorException。我已经让它像这样与 cssSelector 一起工作了...

driver.findElement(By.cssSelector(input[value$='\/foobar']));

但我仍然很好奇如何使用 xpath 完成此操作。有什么建议吗?

编辑: 我还应该注意,我希望能够在不知道最后一个斜线之前的字符的情况下找到这个元素(又名 /p1/

使用xpath包含函数。相当复杂。可能你不想走这条路。但这也可以做到

//input[contains(@value,'foo') and (not(contains(@value,'foobar1'))) and (not(contains(@value,'foobar2')))]

*记住复杂性,我认为 CssSelector 最适合这种情况。

尝试

//input[@value='/p1/foobar']

如果你不知道它以什么开头,你必须求助于函数:

//input[contains(@value, 'foobar') and substring-after(@value, 'foobar') = '']

这是一个'fiddle'

<?xml version="1.0" encoding="UTF-8"?>
<result>
<input id="" name="checkbox1" onclick="" partition="p1" type="checkbox" value="/p1/foobar1"/>
<input id="" name="checkbox2" onclick="" partition="p1" type="checkbox" value="/p1/foobar"/>
<input id="" name="checkbox3" onclick="" partition="p2" type="checkbox" value="/p2/foobar2"/>
</result>

http://www.xpathtester.com/xpath/4dc56e27ca1674ea0b5b48357214b907

Can I use a Regex in an XPath expression? 中所述,XPath 1.0 不支持正则表达式。

这里有很多例子:

https://msdn.microsoft.com/en-us/library/ms256086(v=vs.110).aspx

这是 XPath 函数列表:

https://msdn.microsoft.com/en-us/library/ms256180(v=vs.110).aspx

XPath 不支持正则表达式。您将不得不求助于其他 XPath 函数,对于您的示例,您可以使用类似的东西:

//input[ends-with(@value,'foobar')]

有一个很好的 XPath 函数列表 here