Malasuerte94
Malasuerte94

Reputation: 1474

Xpath get a if href contains part of string

Hi there I tried to get all elements which contain href=/p/{random}/?tagged=see Here is my line

//div[preceding::h2[text()='Most recent']]/div/div/a[@href='/p/*/?tagged=see']

How I can fix this code, I must replace the '*' with something else?

Upvotes: 8

Views: 10628

Answers (1)

har07
har07

Reputation: 89315

In XPath 2.0 or above, you can use Regex functions, for example :

//a[matches(@href, '/p/.*/\?tagged=see')]

Or using combination of string functions starts-with() and ends-with() :

//a[starts-with(@href, '/p/')]
   [ends-with(@href, '/?tagged=see')]

XPath 1.0 doesn't have regex nor ends-with() functions, however, you can simulate the latter :

//a[starts-with(@href, '/p/')]
   [substring(@href, string-length(@href) - string-length('/?tagged=see') +1) = '/?tagged=see']

Simplified :

//a[starts-with(@href, '/p/')]
   [substring(@href, string-length(@href) - 11) = '/?tagged=see']

Upvotes: 11

Related Questions