日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

python爬蟲(chóng)框架scrapy下載中間件的編寫(xiě)方法_python

作者:S++ ? 更新時(shí)間: 2022-05-28 編程語(yǔ)言

下載中間件

在每一個(gè)scrapy工程中都有一個(gè)名為 middlewares.py 的文件,這個(gè)就是中間件文件
其中下載中間件的類為 XxxDownloaderMiddleware
其中有這么幾個(gè)方法

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

process_request

這個(gè)方法是用來(lái)攔截請(qǐng)求的,我們可以將UA偽裝寫(xiě)在這個(gè)方法中。
UA池這個(gè)屬性需要自己編寫(xiě)

def process_request(self, request, spider):
        # UA偽裝,從UA池隨機(jī)一個(gè)
        request.headers['User-Agent'] = random.choice(self.user_agent_list)
        return None

process_response

這個(gè)方法是用來(lái)攔截響應(yīng)的,我們可以在這里篡改響應(yīng)數(shù)據(jù)。
如果我們將selenium和scrapy結(jié)合就可以請(qǐng)求那些動(dòng)態(tài)加載的數(shù)據(jù)了。

 def process_response(self, request, response, spider):
        # 瀏覽器對(duì)象
        bro = spider.bro
        # 參數(shù)spider是爬蟲(chóng)對(duì)象
        # 挑選出指定響應(yīng)對(duì)象進(jìn)行篡改url->request->response
        bro.get(request.url)
        page_text = bro.page_source  # 包含了動(dòng)態(tài)加載的數(shù)據(jù)
        # 針對(duì)定位到的response篡改
        # 實(shí)例化新的響應(yīng)對(duì)象(包含動(dòng)態(tài)加載的數(shù)據(jù))
        response = HtmlResponse(url=bro.current_url, body=page_text, encoding='utf-8', request=request)
        return response

在爬蟲(chóng)文件中需要預(yù)先創(chuàng)建selenium的瀏覽器對(duì)象

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/網(wǎng)絡(luò)爬蟲(chóng)/study_selenium/chromedriver')
        chrome_options = ChromeOptions()
        # 規(guī)避檢測(cè)
        chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
        # 實(shí)例化瀏覽器
        self.bro = webdriver.Chrome(service=service, options=chrome_options)

process_exception

這是用來(lái)攔截發(fā)生異常的請(qǐng)求對(duì)象,一般我們可以在這里寫(xiě)代理ip。
兩個(gè)代理ip池屬性需要自己編寫(xiě)

 def process_exception(self, request, exception, spider):
        # 可以設(shè)置代理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)
        # 重新請(qǐng)求發(fā)送
        return request

其它

我們需要在settings.py中開(kāi)啟下載中間件才能使其生效

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

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

欄目分類
最近更新