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

115 篇文章 0 订阅
52 篇文章 2 订阅

包含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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值