python scrapy简单模拟登录的代码怎么写
python scrapy简单模拟登录的代码怎么写
今天小编给大家分享一下python scrapy简单模拟登录的代码怎么写的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。
1、requests模块。直接携带cookies请求页面。
找到url,发送post请求存储cookie。
2、selenium(浏览器自动处理cookie)。
找到相应的input标签,输入文本,点击登录。
3、scrapy直接带cookies。
找到url,发送post请求存储cookie。
#-*-coding:utf-8-*-importscrapyimportreclassGithubLoginSpider(scrapy.Spider):name="github_login"allowed_domains=["github.com"]start_urls=["https://github.com/login"]defparse(self,response):#发送Post请求获取Cookiesauthenticity_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}yieldscrapy.FormRequest("https://github.com/session",formdata=form_data,callback=self.after_login)defafter_login(self,response):#验证是否请求成功print(re.findall("LearnGitandGitHubwithoutanycode!",response.body.decode()))
知识点扩展:
parse_login方法是提交完表单后callback回调函数指定要执行的方法,为了验证是否成功。这里我们直接在response中搜索Welcome Liu这个字眼就证明登录成功。
这个好理解,重点是yield from super().start_resquests(),这个代表着如果一旦登录成功后,就直接带着登录成功后Cookie值,方法start_urls里面的地址。
这样的话登录成功后的response可以直接在parse里面写。
#-*-coding:utf-8-*-importscrapyfromscrapyimportFormRequest,RequestclassExampleLoginSpider(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"defparse(self,response):print(response.text)defstart_requests(self):yieldscrapy.Request(self.login_url,callback=self.login)deflogin(self,response):formdata={"email":"liushuo@webscraping.com","password":"12345678"}yieldFormRequest.from_response(response,formdata=formdata,callback=self.parse_login)defparse_login(self,response):#print(">>>>>>>>"+response.text)if"WelcomeLiu"inresponse.text:yieldfromsuper().start_requests()
以上就是“python scrapy简单模拟登录的代码怎么写”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注恰卡编程网行业资讯频道。
推荐阅读
-
Python 3.12 新特性解析:模式匹配增强与性能优化实战
-
Lightly IDE 深度评测:轻量级 Python 开发工具是否适合团队协作?
-
VS Code 自定义配置:JSON 文件修改、代码片段与任务自动化脚本
-
Python 虚拟环境选择:venv、conda、poetry 的适用场景对比
-
PyCharm+GitHub Copilot:Python 开发中 AI 辅助编码的最佳实践
-
PyCharm 无法识别虚拟环境?5 步排查 Python 解释器配置问题
-
数据科学工具链:Jupyter Notebook+RStudio+Python 的协同工作流
-
Python 3.12 新特性:模式匹配增强与性能改进实战
-
Lightly IDE 适合谁?轻量级 Python 开发工具深度评测
-
Python IDE 终极对比:PyCharm vs VS Code vs Jupyter Notebook