【问题标题】:Select by xpath knowing only ending of element's attribute通过 xpath 选择只知道元素属性的结尾
【发布时间】:2015-02-13 08:17:02
【问题描述】:

有这样的 xml 文件。我怎样才能只选择那个标签,href 属性以parent 结尾,就像下面的第三个元素。

按位置确定,例如 elem = tree.findall('{*}CustomProperty')[2] 不适合,因为某些文档可能只有一个 parent href,其他 5-10 和第三个可能根本没有这样的 href。

我倾向于使用 xpath,但不知道如何告诉 xpath 搜索属性匹配的结尾。

xpath 也不是必须的,我很乐意使用任何适合我目的的方式

那么我怎样才能获得CustomProperty 元素,它的href 属性以单词parent 结尾?

 <CustomProperty href="urn:1653267:643562dafewq:cs:46wey5ge:234566">urn:1653267:643562dafewq:cs:46wey5ge:234566:ss</CustomProperty>
 <CustomProperty href="urn:1653267:643562dafewq:cs:46wey5ge:234566">urn:1653267:643562dafewq:cs:46wey5ge:234566:ss</CustomProperty>
 <CustomProperty href="urn:1653267:643562dafewq:cs:46wey5ge:234566:parent">urn:1653267:643562dafewq:cs:46wey5ge:234566:ss</CustomProperty>

提前感谢您的帮助

【问题讨论】:

    标签: python xml xpath web-scraping lxml


    【解决方案1】:

    会

    //CustomProperty[contains(@href, 'parent') and substring-after(@href, 'parent') = '']
    

    满足您的要求?该建议的一个问题是它对于 parent 多次出现的 href 属性失败。

    如果您的 xpath 处理器支持 xpath 2.0,请使用 aberna 的建议。

    出于性能原因,请记住尽可能用特定路径替换“//”轴。

    【讨论】:

      【解决方案2】:

      尝试使用 contains 选择器查找属性 href 包含单词 parent 的元素

      //*[contains(@href, 'parent')]
      

      或者如果你确定文本“父”的位置,你可以使用end-with

      //*[ends-with(@href, 'parent')]
      

      【讨论】:

      • ends-with 需要支持 xpath 2.0
      • @collapsar,如何确定是否支持 xpath 2.0?我正在使用最新的 lxml 库
      • @micgeronimo 使用需要 xpath 2.0 的位置路径(例如,节点测试中的 ends-with 函数) - 您的处理器应该抛出有关“不支持的功能”或“语法错误”的错误。请注意,xpath 2 非常广泛,因此您使用的处理器可能无法完全支持它。这意味着如果可能的话,请查阅文档;-)
      • @micgeronimo lxml 支持 XPath 1.0、XSLT 1.0 及其扩展 EXSLT - 因为在内部,它使用了 libxslt 和 libxml2。所以,不,不支持 XPath 2.0。
      猜你喜欢
      • 2021-03-14
      • 1970-01-01
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 2019-07-20
      • 2012-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多