Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting elements whose attribute begins with something in XPath

As the title says, is it possible to select elements in XPath that only begin with a certain string, but perhaps do not end with the same?

For example there are 3 anchor elements:

<a href="buy.php/onething"></a><a href="buy.php/twothing"></a><a href="sell.php/anotherthing"></a>

I only want to get anchor elements that begin with 'buy.php/'. I don't think the following will work, will it:

getByXPath("//a[@href='buy.php/']")

How can I do this?

like image 239
Allen Gingrich Avatar asked Jul 21 '10 17:07

Allen Gingrich


People also ask

How do you select the first element with the same XPath?

Use the index to get desired node if xpath is complicated or more than one node present with same xpath. You can give the number which node you want.

How do you locate an element by partially comparing its attributes in XPath?

We can identify elements by partially comparing to its attributes in Selenium with the help of regular expression. In xpath, there is contains () method. It supports partial matching with the value of the attributes. This method comes as useful while dealing with elements having dynamic values in their attributes.


2 Answers

//a[starts-with(@href, 'buy.php/')]

http://www.zvon.org/xxl/XSLTreference/Output/function_starts-with.html

like image 57
MooGoo Avatar answered Oct 11 '22 09:10

MooGoo


Not sure if this is exactly the correct syntax but you probably want to use the fn:contains xpath function. Other useful functions you can find here:

http://www.w3schools.com/xpath/xpath_functions.asp#string

getByXPath("//a[fn:contains(@href/text(), 'buy.php/')]")

like image 3
Michael Bazos Avatar answered Oct 11 '22 08:10

Michael Bazos