当前位置:网站首页>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)
边栏推荐
猜你喜欢
随机推荐
三元判断再三元判断
uniapp | 开发中遇到的兼容性问题(待续)
MySql高级 -- 约束
Kali install IDEA
3. PHP data types, constants, strings and operators
线程池(线程池介绍与使用)
PHP 给图片添加全图水印
When PHP initiates Alipay payment, the order information is garbled and solved
每日五道面试题总结 22/7/19
After the mailbox of the Pagoda Post Office is successfully set up, it can be sent but not received.
[mikehaertl/php-shellcommand] A library for invoking external command operations
PHP 发起支付宝支付时 订单信息乱码解决
(3)Thinkphp6数据库
宝塔邮局邮箱设置成功后能发送不能接收问题处理
DVWA drone installation tutorial
逍遥多开模拟器ADB驱动连接
2. PHP variables, output, EOF, conditional statements
TypeScript 错误 error TS2469、error TS2731 解决办法
项目中遇到的问题
PHP8.2将会有哪些新东西?









