python - 为什么 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
)
解决方案
要删除爬取 的步骤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
推荐阅读
- java - 如何使用 Seq 从数据集中选择列
在 Java 中? - quarkus - Quarkus“运行应用程序”教程
- c# - 如何检索用户在自适应卡中输入的 C# 代码输入以及如何在单击提交按钮时调用下一个意图
- python - 在没有 NA 值的情况下更改 dtype,或者在 pandas 中读取 DF 时更改 dtype?
- react-native - 启用 GPS 后如何导航到屏幕?
- c# - 在 LINQ 中未检测到来自存储过程的用户定义类型
- react-admin - 从特定分支或打开拉取请求安装 React-Admin 包
- python - Django注释计数不起作用总是返回1
- android - react native 执行 aapt 失败
- node.js - 有没有办法用 Jasmine 测试功能而不暴露它们?