简体   繁体   中英

Finding WebElement by Xpath Using Regex

I have the following 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=""/>

And I'm wanting to find the 2nd element in the above source (the one with with a value of /p1/foobar ) based on value attribute using regex in an xpath. I have tried the following:

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

But it throws an InvalidSelectorException. I've gotten it to work with cssSelector like so ...

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

But I'm still curious how to accomplish this with xpath. Any suggestions?

EDIT: I should also note that I want to be able to find this element without knowing the characters before the last slash (aka /p1/ )

Try

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

If you don't know what it starts with, you have to resort to functions:

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

Here is a '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

As noted in Can I use a Regex in an XPath expression? , XPath 1.0 doesn't support regular expressions.

Here are many examples:

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

Here is a list of XPath functions:

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

Use xpath contains function. Fairly complicated. Probably you do not want to go this route. But this can be done also

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

*Keep the complexity in mind, I think the CssSelector is the best fit for this scenario.

XPath does not support regex. You will have to resort to other XPath functions, for your example you can use something like:

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

There is a nice list of XPath functions here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM