scrapy框架XPATH选择器与正则式使用技巧

12 篇文章 0 订阅
1 篇文章 0 订阅

代码示例:

def parse_item(self, response):
    item = NewsItem()
    item['title'] = response.xpath('//h1[@id="chan_newsTitle"]/text()').extract_first()
    item['url'] = response.url   
    item['text']=''.join(response.xpath('//div[@id="chan_newsDetail"]
    //p[not(@class="editor")]/text()').extract()).strip()
    item['datetime'] = response.xpath('//div[@class="chan_newsInfo_source"]
    //text()').re_first('(\d+-\d+-\d+\s\d+:\d+:\d+)')
    item['source'] = response.xpath('//div[@class="chan_newsInfo_source"]
    //text()').re_first('来源:(.*)').strip()
    item['website'] = '中华网'
    yield item

代码分析:

以上代码为解析一篇新闻详情页,链接为:https://tech.china.com/article/20200520/20200520521233.html

1. 对于XPATH中的“//”和“/”的使用:

一般来说,“//”代表提取的节点是子孙节点,“/”代表提取的是直接子节点。

(1)但是,对于提取一个节点的时候,如第6行代码“//p[not(@class="editor")]/text()').extract()).strip()”为提取id为“chan_newsDetail”的div节点下的p节点(直接子节点),在此处使用“//”或“/”都是能够成功提取到p节点的(根据实测结果得知)。

(2)而对于提取一个节点的text()文本的时候需要注意,“/text()”代表提取该节点的文本,“//text()”代表提取该节点的子节点和子孙节点的文本

2. 根据id或者class属性来选取某个节点:

(1)根据id来选取节点:

 如代码的第3行,根据id选取“h1”节点:

//h1[@id="chan_newsTitle"]

(2)根据class来选取节点:

 如代码的第7行,根据class选取“div”节点:

//div[@class="chan_newsInfo_source"]

3.  选取某个属性不是“xxx”的节点:

如代码的第6行,选取class属性值不是“editor”的所有p节点:

//p[not(@class="editor")]

4. 正则表达式的使用:

item['datetime'] = response.xpath('//div[@class="chan_newsInfo_source"]
//text()').re_first('(\d+-\d+-\d+\s\d+:\d+:\d+)')
item['source'] = response.xpath('//div[@class="chan_newsInfo_source"]
//text()').re_first('来源:(.*)').strip()

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值