当前位置:网站首页>Scrapy爬虫遇见重定向301/302问题解决方法
Scrapy爬虫遇见重定向301/302问题解决方法
2022-08-02 03:25:00 【BIG_权】
Scrapy中止重定向
在scrapy爬取数据时,遇到重定向301/302
,特别是爬取一个下载链接时,他会直接重定向并开始下载,在下载之后才会返回爬取的链接,这时候就需要中止重定
以下302都可以换成301,是一样的
中止重定向
yield Request(url,
meta={
'dont_redirect': True,
'handle_httpstatus_list': [302]
},
callback=self.parse)
如果爬取是在parse
中以yield Request
爬取,那么需要添加过滤 dont_filter=True
,详情可见下述情景二
取到response中Location值
重定向后的链接会放在response里header中的Location
,这里说明一下如何取到其中的值
location = response.headers.get("Location")
情景一
如果爬取网址是在start_urls
中顺序爬取执行,直接在start_requests
方法中添加就行
def start_requests(self):
yield Request(url,
meta={
'dont_redirect': True,
'handle_httpstatus_list': [302]
},
callback=self.parse)
完整例子
import scrapy
class xxSpider(scrapy.Spider):
name = 'xx'
allowed_domains = ['www.xxx.com']
start_urls = ['http://www.xxx.com/download']
def start_requests(self):
# 在此直接中止302重定向即可
yield Request(start_urls[0],
meta={
'dont_redirect': True,
'handle_httpstatus_list': [302]
},
callback=self.parse)
def parse(self, response):
# 取得返回的重定向值
location = response.headers.get("Location")
情景二
如果爬取是在parse
中以yield Request
爬取,那么需要添加过滤dont_filter=True
yield Request(url,
meta={
'dont_redirect': True,
'handle_httpstatus_list': [302]
},
callback=self.parse,dont_filter=True)
完整例子
import scrapy
class xxSpider(scrapy.Spider):
name = 'xx'
allowed_domains = ['www.xxx.com']
start_urls = ['http://www.xxx.com/download']
def parse(self, response):
url = "xxxxxxxxxx"
# 在此需要添加过滤
yield Request(url,
meta={
'dont_redirect': True,
'handle_httpstatus_list': [302]
},
callback=self.parse,dont_filter=True)
边栏推荐
猜你喜欢
随机推荐
(3) Thinkphp6 database
IP access control: teach you how to implement an IP firewall with PHP
13.JS输出内容和语法
1.6一些今日学习
npm --package.json---require
一分种一起来了解Vite的基础
Xiaoyao multi-open emulator ADB driver connection
使用PHPMailer发送邮件
Several interesting ways to open PHP: from basic to perverted
[league/flysystem]一个优雅且支持度非常高的文件操作接口
IO流、 编码表、 字符流、 字符缓冲流
批量替换文件字体,简体->繁体
17.JS条件语句和循环,以及数据类型转换
js预编译 GO 和AO
每日五道面试题总结 22/7/23
QR code generation API interface, which can be directly connected as an A tag
6.27面试集
14. JS Statements and Comments, Variables and Data Types
关于tp的apache 的.htaccess文件
TypeScript 错误 error TS2469、error TS2731 解决办法