XPath获取包含部分字符串的href链接

8

您好,我尝试获取所有包含 href=/p/{random}/?tagged=see 的元素。以下是我的代码:

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

我该如何修复这段代码,我必须用其他东西替换 '*' 吗?
1个回答

11

在XPath 2.0或以上版本中,您可以使用正则表达式函数,例如:

//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()函数,但是你可以模拟后者

XPath 1.0没有正则表达式和ends-with()函数,但是你可以模拟后者。
//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']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接