【问题标题】:xpath select node texts and child nodesxpath 选择节点文本和子节点
【发布时间】:2014-11-24 04:56:40
【问题描述】:

我正在使用 python scrapy 从网站上抓取一些数据。

网站内容是这样的

 <html>
  <div class="details">
  <div class="a"> not needed</div>
  content 1
  <p>content 2</p>
  <div>content 2</div>
  <p>content 2</p>
  <div>content 2</div>
  <p>content 2</p>
  <div class="b"> this is also not needed</div>
  </div>
 </html>

我需要获取完整的 html 数据,不包括 a、b 类的 div。

所以我的输出会是这样的

<div class="details">   
content 1
<p>content 2</p>
<div>content 2</div>
<p>content 2</p>
<div>content 2</div>
<p>content 2</p>
</div>

我怎样才能为此编写正确的 xpath,或者我应该为具有类 'details'、'a'、'b' 的 div 编写 xpath 并使用字符串操作来删除具有类 'a'、'b' 的 div?

请注意,这里的内容是 div 的文本,并且不是具有“详细信息”类的 div 的子项

【问题讨论】:

    标签: html xpath web-scraping scrapy


    【解决方案1】:

    您可以使用node()self:: 语法获取除divab 之外的所有子代:

    //div[@class="details"]/node()[not(self::div[@class="a" or @class="b"])]
    

    使用scrapy shell的演示:

    $ scrapy shell index.html
    >>> nodes = response.xpath('//div[@class="details"]/node()[not(self::div[@class="a" or @class="b"])]').extract()
    >>> print ''.join(nodes)
      content 1
      <p>content 2</p>
      <div>content 2</div>
      <p>content 2</p>
      <div>content 2</div>
      <p>content 2</p>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-15
      • 1970-01-01
      • 2011-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多