Xpath得到一个if href包含字符串的一部分

时间:2017-03-20 10:22:07

标签: html dom xpath css-selectors

您好,我试图获取包含href = / p / {random} /?tagged = see的所有元素 这是我的行

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

我如何修复此代码,我必须更换' *'与其他东西?

1 个答案:

答案 0 :(得分:4)

在XPath 2.0或更高版本中,您可以使用Regex函数,例如:

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

或使用字符串函数starts-with()ends-with()

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

XPath 1.0没有正则表达式和ends-with()函数,但是,您可以simulate the latter

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

简化:

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