【问题标题】:Xpath get a if href contains part of stringXpath获取一个if href包含字符串的一部分
【发布时间】:2017-08-11 13:58:26
【问题描述】:

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

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

如何修复此代码,我必须将“*”替换为其他内容?

【问题讨论】:

    标签: html dom xpath css-selectors


    【解决方案1】:

    在 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']
    

    【讨论】:

      猜你喜欢
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      • 2016-06-13
      相关资源
      最近更新 更多