python爬虫29 | 使用scrapy爬取糗事百科的例子,告诉你它有多厉害!
是时候给你说说
爬虫框架了
使用框架来爬取数据
会节省我们更多时间
很快就能抓取到我们想要抓取的内容
框架集合了许多操作
比如请求,数据解析,存储等等
都可以由框架完成

有些小伙伴就要问了
你他妈的
为什么不早点说呢?

是这样的
当你不知道 1+1 是什么的时候
你去使用计算器来计算
也是没用的
对吧
所以框架的使用
在现在这个时候(爬虫28篇之后)讲
就是一个不错的时机

今天
小帅b就跟你说说
scrapy这个框架
到底有多牛b
那么
接下来就是
学习 python 的正确姿势

要使用 scrapy
首先当然你得需要有啊
你可以使用 conda 安装
conda install -c conda-forge scrapy
你也可以使用 PyPI 安装
pip install Scrapy
scrapy依赖一些相关的库
lxml
parsel
w3lib
twisted
cryptography and pyOpenSSL
如果你在使用 scrapy 的时候发现相关库缺失
把裤子穿上就是了
哦不是
把你缺失的库安装上就完事了

好了
现在假设你已经安装好了 scrapy 这个框架
那么接下来
小帅b会带你使用它来爬取一下 糗事百科 的段子
主要让你知道 scrapy 的使用以及体验它的牛逼之处
废话不多说
在你想要存放的爬虫文件目录下
使用命令来创建一个 scrapy 爬虫项目
比如在这里
我们要创建一个 qiushibaike 的爬虫项目
就可以这样
scrapy startproject qiushibaike
这时候你就会发现
scrapy帮你自动生成了项目文件

在这里面有一些配置文件和预定义的设置文件
而我们的爬虫代码
可以在 spiders 目录下创建
在这里我们就创建一个 qiushibaike_spider 吧

要使用 scrapy 爬虫
我们就需要继承 scrapy.Spider 这个类
这样我们才能使用它定义的一些方法
class QiushiSpider(scrapy.Spider):
接着我们要定义一个爬虫的名称
这里定义一个唯一的名称
用来标识糗事的爬虫
在项目中不能和别的爬虫名称一样
等会会用到这个名称
name = "qiushibaike"
接着我们就可以来定义我们的请求了
比如我们要爬糗事百科的段子的第一和第二页
所以我们可以这样定义请求链接
def start_requests(self):
urls = [
'https://www.qiushibaike.com/text/page/1/',
'https://www.qiushibaike.com/text/page/2/',
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
我们在这个方法 start_requests 需要返回一个 yield 生成的迭代
而其中的参数 callback=self.parse 就是要让它去回调我们的数据解析方法
回调方法是这样的
def parse(self, response):
page = response.url.split("/")[-2]
filename = 'qiushi-%s.html' % page
with open(filename, 'wb') as f:
f.write(response.body)
self.log('Saved file %s' % filename)
主要是把我们抓取下来的 html 存入到本地文件
我们来使用 scrapy 运行一下这个爬虫
使用如下命令即可
cd qiushibaike/
scrapy crawl qiushibaike
scrapy crawl qiushibaike 中的 qiushibaike 就是我们刚刚定义的名称
不过这个时候运行后你会发现报错了

这是因为你懂得
糗事做了反爬
我们定义一个 header 吧
haders = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/73.0.3683.86 Chrome/73.0.3683.86 Safari/537.36'
}
def start_requests(self):
urls = [
'https://www.qiushibaike.com/text/page/12/',
'https://www.qiushibaike.com/text/page/2/',
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse, headers=self.haders)
再次运行命令
scrapy crawl qiushibaike
这次可以发现
源代码被我们爬取下来了

是不是很方便咧
接下来我们再来解析关键数据
比如我们只需要段子的作者和段子的内容
scrapy 也内置了 css、xpath 选择器的解析了
而且
scrapy 还内置了很多好用的命令
我们可以使用 scrapy shell 来请求我们的网页
scrapy shell /home/wistbean/PycharmProjects/spider/qiushibaike/qiushi-1.html
shell 后面可以是你爬下来的 HTML 文件
也可以是你一个链接
进去之后是这样的

我们可以在这里面做一些命令操作了
比如我们在这里坐一下解析操作
打开我们刚刚要爬的糗事百科的链接

可以看到
每个段子都被包含在一个 id 为 content-left 的 div 里面
我们使用如下命令获取
>>> content_left_div = response.xpath('//*[@id="content-left"]')
接着我们获取它下面的所有 div
>>> content_list_div = content_left_div.xpath('./div')
我们试着获取这个页面的所有作者名称和内容

作者名称位于 a 标签下的 h2

内容位于div下的span
我们还是一样
通过 xpath 获取
我们先来获取一个条目看看
content_div = content_list_div[0]
获取作者名称
>>> author = content_div.xpath('./div/a[2]/h2/text()').get()
>>> print(author)
街角*
获取段子内容
>>> content = content_div.xpath('./a/div/span/text()').getall()
>>> print(content)
['\n\n\n刚上小学一年级时,一次肚子有点不舒服拉肚子,跑到厕所后运动裤上面的绳子竟然打了死结,在厕所里面如无头苍蝇一样乱转。', '这时看到老师在旁边上蹲坑,也不顾难为情了'此时老师蹲在蹲坑躲闪不及,浑身上下星星点点,屎喷了满脸如同长满麻子般!', '又是开心的一天,没有拉裤子!\n\n']
>>>
这样
我们就通过命令行的方式可以知道如何获取我们想要的数据了
回到代码来
我们把 parse 方法改成这样
def parse(self, response):
content_left_div = response.xpath('//*[@id="content-left"]')
content_list_div = content_left_div.xpath('./div')
for content_div in content_list_div:
yield {
'author': content_div.xpath('./div/a[2]/h2/text()').get(),
'content': content_div.xpath('./a/div/span/text()').getall(),
}
然后再使用命令行运行
scrapy crawl qiushibaike
可以看到我们要的信息被打印出来了

那么
要将爬下来的数据存储为 json 文件怎么办呢
一个命令就搞定了
scrapy crawl qiushibaike -o qiushibaike.json
运行之后你会看到你的项目下多了一个 json 文件

不过中文乱码了
在 settings.py 中加一句
FEED_EXPORT_ENCODING = 'utf-8'
我们在运行一下

中文回来了

什么?
你想实现翻页抓取所有内容?
还想保存到数据库里?
好吧
篇幅有限
今天就到这里
且听帅b下回讲解
peace