【问题标题】:Select divs between html comments in lxml在lxml中的html注释之间选择div
【发布时间】:2011-12-24 10:55:46
【问题描述】:

这是我的html文件

<div>
   <div></div>
   <div></div>
   <!--Comment1-->
   <div>1</div>
   <div>2</div>
   <div>3</div>
   <!--Comment2-->
   <div></div>
   <div></div>
   <div></div>
</div>

我想在评论 1 和评论 2 之间选择 div

有了这个 xPath = "/div/comment()" 我可以选择&lt;!--Comment1--&gt;&lt;!--Comment2--&gt;

但我想选择这个

   <div>1</div>
   <div>2</div>
   <div>3</div>

【问题讨论】:

  • 我刚刚更改了你的 div,因为你有它们 &lt;div&gt;&lt;div/&gt; 所以如果你尝试了一些东西并且它没有工作,请先仔细检查。
  • 这里有一篇文章,有一个插件,bennadel.com/blog/… 但不确定它是如何工作的,
  • 这是另一个答案,stackoverflow.com/questions/1623734/…
  • 感谢您更改我刚刚手动编写的 div,因此它们是错误的。其实这是一个非常大的文件!
  • 我正在尝试使用 lxml (python) 而不是 javascript!还是谢谢

标签: python html xml parsing xpath


【解决方案1】:
//*[preceding-sibling::comment() and following-sibling::comment()]

或更严格的版本:

//*[preceding-sibling::comment()[. = 'Comment1'] 
    and following-sibling::comment()[. = 'Comment2']]

【讨论】:

    【解决方案2】:

    在 XPath 1.0 中,可以使用通用 (Kayessian) 方法进行两个节点集 $ns1$ns2 的交集

    $ns1[count(.|$ns2) = count($ns2)]
    

    当我们将$ns1$ns2 替换为针对这种特殊情况的特定选择表达式时,我们得到:

    /*/comment()[1]/following-sibling::div
                [count(. | /*/comment()[2]/preceding-sibling::div)
                =
                 count(/*/comment()[2]/preceding-sibling::div)
                ]
    

    基于 XSLT 的验证

    <xsl:stylesheet version="1.0"
     xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
     <xsl:output omit-xml-declaration="yes" indent="yes"/>
    
     <xsl:template match="/">
         <xsl:copy-of select=
         "/*/comment()[1]/following-sibling::div
                [count(. | /*/comment()[2]/preceding-sibling::div)
                =
                 count(/*/comment()[2]/preceding-sibling::div)
                ]
         "/>
     </xsl:template>
    </xsl:stylesheet>
    

    当此转换应用于提供的 XML 文档时

    <div>
       <div></div>
       <div></div>
       <!--Comment1-->
       <div>1</div>
       <div>2</div>
       <div>3</div>
       <!--Comment2-->
       <div></div>
       <div></div>
       <div></div>
    </div>
    

    选择并输出所需的确切节点

    <div>1</div>
    <div>2</div>
    <div>3</div>
    

    在 XPath 2.0 中使用intersect 运算符:

      /*/comment()[1]/following-sibling::div
    intersect
     /*/comment()[2]/preceding-sibling::div
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-24
      • 2018-03-16
      • 2016-03-26
      • 1970-01-01
      相关资源
      最近更新 更多