脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python爬虫框架scrapy下载中间件的编写方法

python爬虫框架scrapy下载中间件的编写方法

2022-11-13 10:45S++ Python

这篇文章主要介绍了python爬虫框架scrapy下载中间件,在每一个scrapy工程中都有一个名为 middlewares.py 的文件,这个就是中间件文件,本文通过示例代码给大家介绍的非常详细,需要的朋友参考下吧

下载中间件

在每一个scrapy工程中都有一个名为 middlewares.py 的文件,这个就是中间件文件
其中下载中间件的类为 XxxDownloaderMiddleware
其中有这么几个方法

?
1
2
def process_request(self, request, spider):
return None
?
1
2
def process_response(self, request, response, spider):
return response
?
1
2
def process_exception(self, request, exception, spider):
pass

process_request

这个方法是用来拦截请求的,我们可以将UA伪装写在这个方法中。
UA池这个属性需要自己编写

?
1
2
3
4
def process_request(self, request, spider):
        # UA伪装,从UA池随机一个
        request.headers['User-Agent'] = random.choice(self.user_agent_list)
        return None

process_response

这个方法是用来拦截响应的,我们可以在这里篡改响应数据。
如果我们将selenium和scrapy结合就可以请求那些动态加载的数据了。

?
1
2
3
4
5
6
7
8
9
10
11
def process_response(self, request, response, spider):
       # 浏览器对象
       bro = spider.bro
       # 参数spider是爬虫对象
       # 挑选出指定响应对象进行篡改url->request->response
       bro.get(request.url)
       page_text = bro.page_source  # 包含了动态加载的数据
       # 针对定位到的response篡改
       # 实例化新的响应对象(包含动态加载的数据)
       response = HtmlResponse(url=bro.current_url, body=page_text, encoding='utf-8', request=request)
       return response

在爬虫文件中需要预先创建selenium的浏览器对象

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import scrapy
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver import ChromeOptions
 
class XxxSpider(scrapy.Spider):
    name = 'xxx'
    # allowed_domains = ['www.xxx.com']
    start_urls = ['……']
    def __init__(self):
        service = Service('/Users/soutsukyou/PyCharm_Workspace/网络爬虫/study_selenium/chromedriver')
        chrome_options = ChromeOptions()
        # 规避检测
        chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
        # 实例化浏览器
        self.bro = webdriver.Chrome(service=service, options=chrome_options)

process_exception

这是用来拦截发生异常的请求对象,一般我们可以在这里写代理ip。
两个代理ip池属性需要自己编写

?
1
2
3
4
5
6
7
8
def process_exception(self, request, exception, spider):
       # 可以设置代理ip
       if request.url.split(':')[0] == 'http':
           request.meta['proxy'] = 'http://'+random.choice(self.PROXY_http)
       if request.url.split(':')[0] == 'https':
           request.meta['proxy'] = 'https://'+random.choice(self.PROXY_https)
       # 重新请求发送
       return request

其它

我们需要在settings.py中开启下载中间件才能使其生效

?
1
2
3
4
5
# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   'xxx.middlewares.XxxDownloaderMiddleware': 543,
}

到此这篇关于python爬虫框架scrapy下载中间件的编写方法的文章就介绍到这了,更多相关python scrapy中间件内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/S2Jgogo/p/16052157.html

延伸 · 阅读

精彩推荐