【问题标题】:Xpath for extracting everything between two known divsXpath 用于提取两个已知 div 之间的所有内容
【发布时间】:2015-07-24 23:01:46
【问题描述】:

是否可以在两个已知div之间选择任意数量的div,如下所示,

div[@class="foo"]
div[@id="dog"]
div[@id="cat"]
div[@id="horse"]
div[@class="bar"]
div[@class="clearall"]
div[@class="foo"]
div[@id="sheep"]
div[@id="monkey"]
div[@class="bar"]
...etc.

我想选择每个组中div[@class="foo"]div[@class="bar"] 之间的所有 div。不知道中间会有多少个div,因人而异。

我尝试过考虑前兄弟和后兄弟,但我只能选择与已知 div“最近”的 div。

【问题讨论】:

    标签: python html xpath scrapy


    【解决方案1】:

    是的,这是可能的。这里的技巧是使用来自Scrapy XSLT extensions 的集合操作。

    这个想法是,对于每个div[@class='foo'],选择它之后的所有内容减去div[@class='bar']之后的内容

    以下是 Scrapy shell 中的示例,使用的是我在本地创建的 HTML:

    >>> print response.body
    <div class="foo"></div>
    <div id="dog"></div>
    <div id="cat"></div>
    <div id="horse"></div>
    <div class="bar"></div>
    <div class="clearall"></div>
    <div class="foo"></div>
    <div id="sheep"></div>
    <div id="monkey"></div>
    <div class="bar"></div>
    
    >>> after_foo = "following::*[not(@class='bar')]"
    >>> after_first_bar = "./following::div[@class='bar'][1]/following::*"
    >>> xpath_diff = "set:difference(%s, %s)" % (after_foo, after_first_bar)
    >>> for foo in response.xpath("//div[@class='foo']"):
       ...:     print foo.xpath(diff_xpath).extract()
       ...:     
    [u'<div id="dog"></div>', u'<div id="cat"></div>', u'<div id="horse"></div>']
    [u'<div id="sheep"></div>', u'<div id="monkey"></div>']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 2012-02-15
      • 1970-01-01
      • 1970-01-01
      • 2019-09-21
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      相关资源
      最近更新 更多