Scrapy基础——Cookies和Session

我在Python爬虫基础-模拟登陆曾经谈过Cookies和Session。那么如何我想使用Scrapy进行模拟登陆,那么肯定要逃不过Cookies和Session。这篇文章主要为了解决下图这个问题,即如何管理为每一个独立的请求保留其对应的cookies。

img_ea971e904f22522c5350af2c27758e53.png
图片来自互联网

幸运的是官方文档给了解决方案。

Multiple cookie sessions per spider

There is support for keeping multiple cookie sessions per spider by using the cookiejar
Request meta key. By default it uses a single cookie jar (session), but you can pass an identifier to use different ones.

官方给出的例子:

for i, url in enumerate(urls):
    yield scrapy.Request(url, meta={'cookiejar': i},
        callback=self.parse_page)
    ##请记住,cookjar元键(meta key)不会一直保留。你需要在后续请求重进行传递。 例如:
    Keep in mind that the cookiejar meta key is not “sticky”. 
    You need to keep passing it along on subsequent requests. For example:

def parse_page(self, response):
    # do some processing
    return scrapy.Request("http://www.example.com/otherpage",
        meta={'cookiejar': response.meta['cookiejar']},
        callback=self.parse_other_page)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值