当前位置:网站首页>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)
边栏推荐
- js预编译 GO 和AO
- Pycharm打包项目为exe文件
- Xiaoyao multi-open emulator ADB driver connection
- [symfony/mailer] An elegant and easy-to-use mail library
- When PHP initiates Alipay payment, the order information is garbled and solved
- About the apache .htaccess file of tp
- v-on基本使用、参数传递、修饰词
- 12. What is JS
- (6) 学生信息管理系统设计
- PHP的几个有趣的打开方式:从基本到变态
猜你喜欢
随机推荐
12. What is JS
[symfony/mailer] An elegant and easy-to-use mail library
每日面试题 2022/7/28
The Error in the render: "TypeError: always read the properties of null '0' (reading)" Error solution
IP access control: teach you how to implement an IP firewall with PHP
ES6数组的扩展方法map、filter、reduce、fill和数组遍历for…in for…of arr.forEach
TCP communications program
PHP图片压缩到指定的大小
Kali install IDEA
[league/climate]一个功能健全的命令行功能操作库
vim编辑模式
Thread Pool (Introduction and Use of Thread Pool)
MySql高级 -- 约束
16. JS events, string and operator
1.10今日学习
vim edit mode
PHP的几个有趣的打开方式:从基本到变态
使用PHPMailer发送邮件
Small program van-cell line wrapping can be left-aligned
js eventLoop 事件循环机制