«

scrapy模拟登陆

时间:2023-3-1 00:11     作者:wen     分类: Python


一、回顾之前的模拟登陆方法

  1. requests模块是如何实现登陆的?

    1. 直接携带cookies请求页面
    2. 找URL地址,发送post请求存储cookie
  2. selenium是如何模拟登陆的?

    1. 找到对象的input标签,输入文本点击登陆
  3. scrapy的模拟登陆

    1. 直接携带cookies
    2. 找URL地址,发送post请求存储cookie

二、scrapy携带cookies直接获取需要登陆后的页面

应用场景

  1. 实现:重构scrapy的start_requests方法

    # 源代码
    def start_requests(self):
    cls = self.__class__
    if not self.start_urls and hasattr(self, 'start_url'):
        raise AttributeError(
            "Crawling could not start: 'start_urls' not found "
            "or empty (but found 'start_url' attribute instead, "
            "did you miss an 's'?)")
    if method_is_overridden(cls, Spider, 'make_requests_from_url'):
        warnings.warn(
            "Spider.make_requests_from_url method is deprecated; it "
            "won't be called in future Scrapy releases. Please "
            "override Spider.start_requests method instead "
            f"(see {cls.__module__}.{cls.__name__}).",
        )
        for url in self.start_urls:
            yield self.make_requests_from_url(url)
    else:
        for url in self.start_urls:
            yield Request(url, dont_filter=True)

    所以对于的,如果start_url地址中的url是需要登陆后才能访问的URL地址,则需要重写start_requests方法并在其中手动添加上cookies

  2. 携带cookie登陆

    def start_requests(self):
    url = self.start_urls[0]
    temp = "xxx"   # 在网页复制的cookie
    cookies = {data.split('=')[0]: data.split('=')[-1] for data in temp.split('; ')}
    yield scrapy.Request(url=url,callback=self.parse, cookies=cookies)

    注意:scrapy中cookie不能够放在headers中,在构造请求的时候有专门的cookies参数,能够接收字典形式的cookie

三、scrapy.Request发送post请求

我们可以通过scrapy.Request()指定method、body参数来发送post请求;但是通常使用scrapy.FormRequest()来发送post请求
发送post请求
注意:scrapy.FormRequest()能够发送表单和ajax请求

  1. 思路分析
    • 找到post的url地址:点击登陆按钮进行抓包,然后定位URL地址为xxx
    • 找到请求体的规律:分析post请求的请求体,其中包含的参数均在前一次的响应中
    • 是否登陆成功:通过请求个人主页,观察是否包含用户名
  2. 代码实现如下:
    
    allowed_domains = ['github.com']
    start_urls = ['https://github.com/login']

def parse(self, response):
url = "https://github.com/session" ;

分析链接,获取post谁

post_data = {}
# 发送post请求
yield scrapy.FormRequest(url=url,callback=self.after_login, formdata=post_data)

def after_login(self, response):

pass

标签: 爬虫