Search This Blog

Subscribe:

Tuesday, October 26, 2010

Use regex in Selenium locators

To use regex in Xpath locators.

You need to use the regex matches() function, like this:

xpath=//div[matches(@id,'che.*boxes')]



this will click the div with 'id=checkboxes', or 'id=cheANYTHINGHEREboxes')
To get all the links elements with attribute href that match:
http://[^/]*\d+com

Use
sel.get_attribute( '//a[regx:match(@href,
"http://[^/]*\d+.com")]/@name'
)
which will
return a list of the name attribute of
all the links that match the regex.

Be aware, that the matches function is not supported by all
native browser implementations of Xpath
(most conspicuously, using this in FF3 will throw an error: invalid xpath[2]).
If you have trouble with your particular browser (as I did with FF3), try using Selenium's allowNativeXpath("false") to switch over to the JavaScript Xpath interpreter. It'll be slower,
but it does seem to work with more Xpath functions, including 'matches' and 'ends-with'.




0 comments:

Post a Comment