首页 > 解决方案 > 为什么 Scrapy 在爬取主 url 之前会爬取其他一些 url?

问题描述

我要抓取的主要 url 是http://192.168.1.1/adslconfig.htm,但它首先尝试抓取这个 URL http://192.168.1.1/robots.txt,它失败了,状态码为 401,并且它的引用标头也设置为 None,所以它只是浪费了几秒钟。

这不是唯一的,它还尝试抓取我想要的主 URL,但一开始它失败了,引用标头设置为 None

但是在第二次尝试中,它成功了,状态码为 200,referer 标头为http://192.168.1.1/adslconfig.htm

是否因为引用标头而失败?

怎样才能防止这两次爬取不成功,第一次尝试爬取主URL?

在此处输入图像描述

import scrapy

class ScrapperSpider(scrapy.Spider):
    handle_httpstatus_list = [401]
    name = "scrapper"
    start_urls = ["http://192.168.1.1/adslconfig.htm"]
    auth = "Basic YWRtaW46YWRtaW4="

    def parse(self, response):
        return scrapy.Request(
            "http://192.168.1.1/adslconfig.htm",
            headers={'Authorization': self.auth, 'Referer': "http://192.168.1.1/adslconfig.htm"},
            callback=self.after_login
        )

标签: pythonweb-scrapingscrapyweb-crawler

解决方案


要删除爬取 的步骤robots.txt,我ROBOTSTXT_OBEY = False在 settings.py 文件中设置了 ,所以它会忽略robots.txt读取首先抓取 robots.txt?

对于失败的第二步,我不得不将parse方法更改为start_requests

由此:

def parse(self, response):
    return scrapy.Request(
        "http://192.168.1.1/adslconfig.htm",
        headers={'Authorization': self.auth, 'Referer': "http://192.168.1.1/adslconfig.htm"},
        callback=self.after_login
    )

对此:

def start_requests(self):
    return [scrapy.Request(
        "http://192.168.1.1/adslconfig.htm",
        headers={'Authorization': self.auth, 'Referer': "http://192.168.1.1/adslconfig.htm"},
        callback=self.after_login
    )]

请注意,该start_requests方法返回一个可迭代对象,因此它被包装在一个[]

这样,spider 使用这个方法和正确的 headers 并在第一次爬取时应用它们,现在它在第一次尝试时爬取成功!

在此处输入图像描述

要了解该start_requests方法: https ://docs.scrapy.org/en/latest/topics/spiders.html


推荐阅读