1. 程式人生 > >Scrapy新增使用者代理的方法

Scrapy新增使用者代理的方法

參考:http://scrapy-chs.readthedocs.io/zh_CN/0.24/topics/downloader-middleware.html#id2

1、settings.py中新增下載中介軟體

DOWNLOADER_MIDDLEWARES = {
    'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': 125,
    'lianjia.middlewares.UAPOOLS': 126,
}

2、middlewares.py中新增程式碼

from scrapy import signals
import random
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware


class UAPOOLS(UserAgentMiddleware):
    def __init__(self, user_agent=''):
        self.user_agent = user_agent

    def process_request(self, request, spider):
        '''使用代理UA,隨機選用'''
        ua = random.choice(self.user_agent_pools)
        print('當前使用的user-agent是' + ua)
        request.headers.setdefault('User-Agent', ua)

    user_agent_pools = [
        'Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3',
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.75 Safari/537.36',
    ]