python scrapy实现模拟登录功能

发布时间:2021-07-19 12:16:00 作者:chen
来源:亿速云 阅读:197

本篇内容介绍了“python scrapy实现模拟登录功能”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

1、requests模块。直接携带cookies请求页面。

找到url,发送post请求存储cookie。

2、selenium(浏览器自动处理cookie)。

找到相应的input标签,输入文本,点击登录。

3、scrapy直接带cookies。

找到url,发送post请求存储cookie。

# -*- coding: utf-8 -*-
import scrapy
import re
 
class GithubLoginSpider(scrapy.Spider):
    name = 'github_login'
    allowed_domains = ['github.com']
    start_urls = ['https://github.com/login']
 
    def parse(self, response): # 发送Post请求获取Cookies
        authenticity_token = response.xpath('//input[@name="authenticity_token"]/@value').extract_first()
        utf8 = response.xpath('//input[@name="utf8"]/@value').extract_first()
        commit = response.xpath('//input[@name="commit"]/@value').extract_first()
        form_data = {
            'login': 'pengjunlee@163.com',
            'password': '123456',
            'webauthn-support': 'supported',
            'authenticity_token': authenticity_token,
            'utf8': utf8,
            'commit': commit}
        yield scrapy.FormRequest("https://github.com/session", formdata=form_data, callback=self.after_login)
 
    def after_login(self, response): # 验证是否请求成功
        print(re.findall('Learn Git and GitHub without any code!', response.body.decode()))

知识点扩展:

parse_login方法是提交完表单后callback回调函数指定要执行的方法,为了验证是否成功。这里我们直接在response中搜索Welcome Liu这个字眼就证明登录成功。

这个好理解,重点是yield from super().start_resquests(),这个代表着如果一旦登录成功后,就直接带着登录成功后Cookie值,方法start_urls里面的地址。

这样的话登录成功后的response可以直接在parse里面写。

# -*- coding: utf-8 -*-
import scrapy
from scrapy import FormRequest,Request


class ExampleLoginSpider(scrapy.Spider):
    name = "login_"
    allowed_domains = ["example.webscraping.com"]
    start_urls = ['http://example.webscraping.com/user/profile']
    login_url = 'http://example.webscraping.com/places/default/user/login'

    def parse(self, response):
        print(response.text)

    def start_requests(self):
        yield scrapy.Request(self.login_url,callback=self.login)

    def login(self,response):
        formdata = {
            'email':'liushuo@webscraping.com','password':'12345678'}
        yield FormRequest.from_response(response,formdata=formdata,
                                        callback=self.parse_login)
    def parse_login(self,response):
        # print('>>>>>>>>'+response.text)
        if 'Welcome Liu' in response.text:
            yield from super().start_requests()

“python scrapy实现模拟登录功能”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!

推荐阅读:
  1. python爬虫豆瓣网的模拟登录实现
  2. 怎么在python中使用scrapy框架模拟登录

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python scrapy

上一篇:javascript如何实现按钮隐藏div

下一篇:python中的EasyOCR库是什么

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》