基于cookie登录
现在,考虑使用scrapy添加cookie信息,这样可以做到简单快捷,但也是不稳定的。
我们将此任务建立在之前的项目book
下,这里,我们仅演示scrapy基于cookie登录。
我们打开已登录的页面,使用开发工具找到cookie,复制值,但是这个值是适合requests但不适合scrapy的格式,所以要进行格式转换,转换成字典:
import re
strs = 'viewed="26397183"; ...; __utmb=30149280.47.10.1643374436'
strList = re.split(r';\S*', strs)
cookie = {}
for items in strList:
item = items.split('=')
key, value = item[0], item[1]
cookie[str(key)] = str(value)
print(cookie)
我们创建一个新的spider,并复制新的cookie格式,只要在scrapy.Request
请求中加入cookie信息,就实现了对应网页的cookie登录:
import scrapy
class LoginSpider(scrapy.Spider):
name = 'login'
allowed_domains = ['xxx.com']
start_urls = ['https://www.xxxx.com/people/2122xxx46/']
profile_url = "https://www.xxxx.com/people/2122xxx46/"
cookie = {'viewed': '"26397183"', ..., ' __utmb': '30149280.47.10.1643374436'}
def start_requests(self):
yield scrapy.Request(self.profile_url, callback=self.parse_profile, cookies=self.cookie)
def parse_profile(self, response):
print(response.text)