【问题标题】:what is the next tag after the specific tag in html using xpathhtml中使用xpath的特定标签之后的下一个标签是什么
【发布时间】:2013-08-05 04:54:42
【问题描述】:

我有这个 HTML 代码:

<a name="apple"></a>
<h3> header1 </h3>
<p> some text </p>
<p> some text1 </p>
<a name="orange"></a>
<h3> header2 </h3>
<p> some text 2 </p>  

我想检索标题标签后的文本,使用如下代码:

for header in tree.iter('h3'):
 paragraph = header.xpath('(.//following::p)[1]')
 if (header.text=="apple"):
    print "%s: %s" % (header.text, paragraph[0].text)

当我有多个&lt;p&gt; 标签时它不起作用。如何找出我的标题后有多少 &lt;p&gt; 标签并检索所有标签?

我使用 python 2.7 和 xpath。

【问题讨论】:

  • 在每个&lt;h3&gt; 之后直到 下一个&lt;h3&gt; 之后都需要所有&lt;p&gt; 吗?还是第一个&lt;h3&gt; 之后的所有内容,包括第二个“header2”?
  • @paul t。每个

    .

    之后的所有

标签: python-2.7 xpath lxml


【解决方案1】:

使用lxml's (itersibling()) 可能更容易,处理兄弟姐妹,而不是后代,然后在必要时处理这些兄弟姐妹的后代。

你可以试试这样的

>>> for heading in root.iter("h3"):
...     print "----", heading
...     for sibling in heading.itersiblings():
...         if sibling.tag == 'h3':
...             break
...         print sibling
... 
---- <Element h3 at 0x1880470>
<Element p at 0x18800b0>
<Element p at 0x1880110>
<Element a at 0x1880170>
---- <Element h3 at 0x1880050>
<Element p at 0x18801d0>
>>> 

如果要使用XPath,可以使用EXSLT的set extension,在lxml(通过"http://exslt.org/sets"命名空间,思路与上面大致相同:

  • 选择所有兄弟姐妹 (following-sibling::*),
  • 但不包括 (set:difference()) 下一个 &lt;h3&gt; 同级 (following-sibling::h3) 和 (| XPath 运算符) 所有后续同级 (following-sibling::h3/following-sibling::*)。

可以这样使用:

>>> following_siblings_untilh3 = lxml.etree.XPath("""
...         set:difference(
...             following-sibling::*,
...             (following-sibling::h3|following-sibling::h3/following-sibling::*))""",
...         namespaces={"set": "http://exslt.org/sets"})
>>> 
>>> for heading in root.iter("h3"):
...     print "----", heading
...     for e in following_siblings_noth3(heading): print e
... 
---- <Element h3 at 0x1880470>
<Element p at 0x18800b0>
<Element p at 0x1880110>
<Element a at 0x1880170>
---- <Element h3 at 0x1880050>
<Element p at 0x18801d0>
>>> 

我相信它可以被简化。 (我还没有找到following-sibling-or-self::h3...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多