【问题标题】:how to change scrapy user agent without settings file如何在没有设置文件的情况下更改scrapy用户代理
【发布时间】:2017-05-30 22:16:53
【问题描述】:

我已经通过脚本实现了我的蜘蛛,就像主要示例一样:

import scrapy

class BlogSpider(scrapy.Spider):
    name = 'blogspider'
    start_urls = ['https://blog.scrapinghub.com']

    def parse(self, response):
        for title in response.css('h2.entry-title'):
            yield {'title': title.css('a ::text').extract_first()}

        next_page = response.css('div.prev-post > a ::attr(href)').extract_first()
        if next_page:
            yield scrapy.Request(response.urljoin(next_page), callback=self.parse)

我运行:

scrapy runspider myspider.py

如果我没有设置或从 startproject 创建,如何更改用户代理?在这里指定:

https://doc.scrapy.org/en/latest/topics/settings.html

【问题讨论】:

    标签: python django scrapy


    【解决方案1】:

    您可以在请求中手动添加标头,以便指定自定义User Agent

    在您的蜘蛛文件中,当您请求时:

    yield scrapy.Request(self.start_urls, callback=self.parse, headers={"User-Agent": "Your Custom User Agent"})
    

    所以你的蜘蛛应该是这样的:

    class BlogSpider(scrapy.Spider):
        name = 'blogspider'
        start_urls = ['https://blog.scrapinghub.com']
    
        def start_requests(self):
            yield scrapy.Request(self.start_urls, callback=self.parse, headers={"User-Agent": "Your Custom User Agent"})
    
        def parse(self, response):
            for title in response.css('h2.entry-title'):
                yield {'title': title.css('a ::text').extract_first()}
    
            next_page = response.css('div.prev-post > a ::attr(href)').extract_first()
            if next_page:
                yield scrapy.Request(response.urljoin(next_page), callback=self.parse, headers={"User-Agent": "Your Custom User Agent"})
    

    【讨论】:

      【解决方案2】:

      USER_AGENT 添加到settings.py 文件中:

      USER_AGENT = "custom_user_agent"
      

      您也可以使用以下方法更改 USER_AGENTcmdline

      scrapy runspider myspider.py -s USER_AGENT="custom_user_agent"
      

      【讨论】:

      • 由于我使用的是django,这是django settings.py吗?
      • 不,这是scrapy的settings.py。
      猜你喜欢
      • 2014-09-08
      • 2017-04-06
      • 1970-01-01
      • 2016-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-25
      相关资源
      最近更新 更多