scrapy数据解析
这节课,我们来看下scrapy
中的数据解析
创建工程
爬取内容:爬取段子网中的段子:https://duanzixing.com/段子/
回顾上节课所学的知识(创建scrapy),我们先来创建工程和爬虫文件:
1.scrapy startproject duanziPro
2.cd duanziPro
3.scrapy genspider duanzi www.xxx.com
创建好后,我们要不要忘记以下2点:
-
修改下settings.py文件
中的配置
-
注释掉爬虫文件里的 :allowed_domains = ['www.xxx.com']
设置好后,我们来爬取下这个网站:
import scrapy
class DuanziSpider(scrapy.Spider):
name = 'duanzi'
# allowed_domains = ['www.xxx.com']
start_urls = ['https://duanzixing.com/段子/']
def parse(self, response):
print(response)
结果是可以正常爬取的。那么我们怎么进行数据解析呢?
肯定是在parse
函数中写解析代码,这里我们可以用xpath
进行数据解析
使用xpath
进行数据解析
跟我们之前的xpath
语法差不多,我们直接分析:
网站源码很简单,我们很容易就定位到了文本内容。
直接右键复制xpath
,利用之前所学的知识进行解析:
def parse(self, response):
article_list = response.xpath('/html/body/section/div/div/article')
for article in article_list:
title = article.xpath('./header/h2/a/@title')[0]
note = article.xpath('./p[2]/text()')[0]
print(title,note)
执行scrapy crawl duanzi
我们发现,爬取是爬去成功了,但解析出来的内容不是字符串数据,说明和etree中的xpath使用方式不同
在scrapy中,xpath返回的列表中存储而是Selector对象,其实我们想要的字符串数据被存储在了该对象的data属性
将Selector对象data属性值取出
title = article.xpath('./header/h2/a/@title')extract_first()
note = article.xpath('./p[2]/text()')extract_first()
执行后,我们就取到了数据:
上面是最常用的取数据方式,还有下面2种:
# extract()就是将data属性值取出(几乎不用):
title = article.xpath('./header/h2/a/@title')[0].extract()
note = article.xpath('./p[2]/text()')[0].extract()
# 直接使用列表调用extract():可以将列表中的每一个列表元素表示的Selector中的data取出
title = article.xpath('./header/h2/a/@title').extract()
note = article.xpath('./p[2]/text()').extract()
完整代码:
import scrapy
class DuanziSpider(scrapy.Spider):
name = 'duanzi'
# allowed_domains = ['www.xxx.com']
start_urls = ['https://duanzixing.com/段子/']
def parse(self, response):
article_list = response.xpath('/html/body/section/div/div/article')
for article in article_list:
title = article.xpath('./header/h2/a/@title').extract_first()
note = article.xpath('./p[2]/text()').extract_first()
print(title, note)
关注Python涛哥!学习更多Python知识!