马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 LJZheng 于 2021-6-25 23:42 编辑
不知道大家是什么时候开始学Python爬虫的?对于python的爬虫框架有多少的了解?我是2019年开始学的Python,不久后就学了爬虫。
一直以来requests库的简洁明了吸引了我,但架不住他也简洁过头了,称不上是框架,无法有效的组织起复杂的爬虫代码,稍微复杂一些的逻辑就是一坨难以维护的屎山;但是像scrapy这样的框架学起来也着实费力,主要是自己没有大的需求,学起来没动力。
因此我需要一个简洁明了的爬虫框架,简单到可以不需要import,直接复制粘贴到文件里都不会觉得难以维护。
我之前学了前端的vue,每一个组件都有一个生命周期,从创建到销毁,我只需要编写每个组件在不同的时候需要做的事情即可。同时我在学习SpringBoot的时候意识到框架的作用是让开发者更好的关心具体的业务逻辑代码。
根据我自己的想法,我写了一个适合自己的爬虫模板,代码简洁可以按需修改
- from collections import defaultdict
- import requests
- DEFAULT_GET_OPTIONS = {
- 'headers': {
- 'user-agent': 'Mozilla/5.0'
- }
- }
- class Spider:
- def __init__(self, url='', method='GET', options=DEFAULT_GET_OPTIONS, pipe: defaultdict = defaultdict(int)):
- self.url = url
- self.method = method
- self.options = options
- self.pipe = pipe
- self._kill = False
- def run(self):
- # print(self.url)
- self.before()
- if self.killed():
- print(f'request killed: {self.url}')
- else:
- res = requests.request(self.method, self.url, **self.options)
- res.encoding = res.apparent_encoding
- if res.status_code == 200:
- self.callback(res)
- else:
- self.callback_err(res)
- self.after()
- def before(self):
- pass
- def callback(self, res: requests.Response):
- pass
- def callback_err(self, res):
- print(res)
- def after(self):
- self.kill()
- def killed(self):
- return self._kill
- def kill(self):
- self._kill = True
复制代码
整个想法就是所有的爬虫都能够继承上面这个Spider的类,然后根据自己的需要修改代码,最后调用run()方法即可,具体的操作如下所示:
- # 定义一个自己的 Spider 类
- class MySpider(Spider):
- def __init__(self, url='', method='GET', options=DEFAULT_GET_OPTIONS, pipe=defaultdict(int)):
- # 这里也可以写点东西,但是不建议
- super().__init__(url=url, method=method, options=options, pipe=pipe)
- # 下面四个方法可以根据自己的需要修改
- def before(self):
- # 在发起请求之前做的事情
- # 在这里设置 url、method、options 是有效的
- return super().before()
-
- def callback(self, res):
- # 请求发起后对res的处理
- return super().callback(res)
- def callback_err(self, res):
- # 请求失败情况的处理
- return super().callback_err(res)
- def after(self):
- # 请求处理后做的事情
- # 比如time.sleep()、打印日志、或者调用其他的爬虫
- return super().after()
- # 运行的方法
- MySpider(
- # 各种参数
- # url: 对 url发起请求
- # method:请求的方法,默认 GET
- # options: 请求的一些可选的设置,是一个字典的形式,
- # pipe:传入 Spider 里的一些参数,可对 Spider 进行一些定制化的操作
- ).run()
复制代码
Spider中的url,method和options 对应的分别是 requests.request(method, url, **kwargs) 中的url,method和kwargs,因此options要传入一个字典,顺带一提,run()里面的代码逻辑已经非常一目了然了,就不讲了
讲一下pipe的用法,pipe其实就是一个用字典传参的东西,相当于一个容器,啥都可以往里面装,用于定制一些需要的参数(可能主要是我菜,不会用**kwargs吧 )。还有一个 _kill 的参数可以用来控制爬虫是否执行请求,在before()里面设置一下就行了。这里有一个图片爬取的例子:
- import os
- import time
- DEFAULT_IMG_GET_OPTIONS = {
- 'headers': {
- 'user-agent': 'Mozilla/5.0',
- 'Accept-Encoding': 'gzip, deflate'
- }
- }
- def exists(path: str):
- return os.path.exists(path)
- def mkdir(path: str):
- if not os.path.exists(path):
- os.makedirs(path)
- def write(path, data):
- with open(path, 'wb') as f:
- f.write(data)
- class Img_Spider(Spider):
- """
- # init run
- Img_Spider(
- url=r'http://images.dmzj1.com/b/%E5%88%AB%E5%BD%93%E6%AC%A7%E5%B0%BC%E9%85%B1%E4%BA%86/%E7%AC%AC1%E8%AF%9D_1491547130/01.jpg',
- pipe={
- 'img_path': './img_path.jpg', # 图片保存的位置(文件名)
- 'sleep': 2 # 爬取图片后休息一下,可以防止服务器压力过大,封ip等情况。
- }
- ).run()
- """
- def __init__(self, url='', method='GET', options=DEFAULT_IMG_GET_OPTIONS, pipe=defaultdict(int)):
- super().__init__(url=url, method=method, options=options, pipe=pipe)
- def before(self):
- path = self.pipe['img_path']
- # 这里展现了 self._kill 的作用
- # 如果文件存在就不发起请求
- if exists(path):
- print(f'文件 {path} 已存在')
- self.kill()
- return super().before()
- def callback(self, res: requests.Response):
- path = self.pipe['img_path']
- write(path, res.content)
- print(f'文件 {path} 已保存')
- return super().callback(res)
- def after(self):
- # 爬取图片后休息一下,可以一定程度上防止服务器压力过大,封ip等情况。
- if 'sleep' in self.pipe:
- time.sleep(self.pipe['sleep'])
复制代码
我个人认为自己写的这个东西能够满足我的需要,也就够了
|