中1:包含HTML标签的所有文字内容提取:string()

包含HTML标签的所有文字内容提取:string()

<div class="post-content" itemprop="articleBody">
       <p>如果你因失去了太阳而流泪,那么你也将失去群星了。 
      <br>If you shed tears when you miss the sun, you also miss the stars. 
      </p>
      <p><a href="http://www.scrapyd.cn"><a href="http://www.scrapyd.cn" target="_blank"><u>scrapy中文网</u></a></a><a href="http://www.scrapyd.cn">http://www.scrapyd.cn</a>)整理</p>        
</div>

如果我们用表达式://div[@class=’post-content’]//text(),你会发现虽然能提取但是一个列表,不是整段文字:

In [4]: response.xpath("//div[@class='post-content']//text()").extract()
Out[4]:
['\n            ',
 '如果你因失去了太阳而流泪,那么你也将失去群星了。 ',
 'If you shed tears when you miss the sun, you also miss the stars. ',
 'scrapy中文网(',
 'http://www.scrapyd.cn',
 ')整理',
 '        ']

那这里我们就用到一个xpath函数:string(),我们可以把表达式这样写:response.xpath(“string(//div[@class=’post-content’])“).extract(),可看到我们没有使用:text(),而是用:string(要提取内容的标签),这样的话就能把数据都提取出来了,而且都合成为一条,并非一个列表,如下:

In [5]: response.xpath("string(//div[@class='post-content'])").extract()
Out[5]: ['\n            如果你因失去了太阳而流泪,那么你也将失去群星了。 If you
shed tears when you miss the sun, you also miss the stars. scrapy中文网(http://
www.scrapyd.cn)整理        ']

参考文献:http://www.scrapyd.cn/doc/186.html

猜你喜欢

转载自blog.csdn.net/u014229742/article/details/82256096