代码示例:
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()