Scrapy爬虫更改请求头

在很多时候,我们在写爬虫的时候需要去修改爬虫的请求头,那么话不多说,下面代码开始

middlewares.py文件中创建请求头的列表,使用random函数来随机调用使用哪个请求头:

middlewares.py

class UserAgentDownloadMiddleware(object):
    '''
    下载器中间件
    在发送下载之前要设置请求头
    '''

    USER_AGENTS = [
        'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36',
        'Mozilla/5.0 (Windows NT 4.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2049.0 Safari/537.36',
        'Mozilla/5.0 (X11; Linux i686; rv:64.0) Gecko/20100101 Firefox/64.0',
        'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:64.0) Gecko/20100101 Firefox/64.0',
    ]

    def process_request(self, request, spider):
        user_agent = random.choice(self.USER_AGENTS)
        request.headers['User-Agent'] = user_agent

在settings.py文件中修改调用的请求头函数(取消注释,调用上面定义的类)

setting.py

DOWNLOADER_MIDDLEWARES = {
   'useragent_demo.middlewares.UserAgentDownloadMiddleware': 543,
}

在scrapy爬虫程序中就可以开始调用:

import scrapy
import json
class HttpbinSpider(scrapy.Spider):
    name = 'httpbin'
    allowed_domains = ['httpbin.org']
    start_urls = ['http://httpbin.org/user-agent']

    def parse(self, response):
        user_agent = json.loads(response.text)['user-agent']
        print('=='*20)
        print(user_agent)
        print('==' * 20)
        yield scrapy.Request(self.start_urls[0], dont_filter=True)  # dont_filter=True 表示不需要去重

然后执行start文件,就可以开始打印出新的请求头了:

from scrapy import cmdline
cmdline.execute("scrapy crawl httpbin".split())

你可能感兴趣的:(爬虫)