2020最新Python零基础到精通资料教材,Python基础入门,Python小白书籍,Python学习路线,Python进阶,Python高级,Python爬虫等等一系列关于Python的文档和视频(包括hadoop,fink,hive,MySQL,spark,算法,Linux)
全都打包好了
需要的请主动找我私信“资料”获取,也可在评论区评论,请说明来意
爬虫脚本是大家经常用到的,那就避开不了登录这一关。
使用Python一般需要request库,补充 header 中的 post 要素,有些还会有 隐藏的 hidden 参数,可以通过浏览器 F12 或者元素审查来发现,对于初学者来说都是一个坑。还有需要解决验证码的问题,一种方法是下载验证码图片识别验证码再次post,或者使用云打码平台。当然,有些验证码及其变态就不那么容易解决了,比如选字顺序、滑块、12306那种人为都会选错的。本篇boy哥分享一个GitHub项目《awesome-python-login-model》,主要就是利用Python解决登录主流平台的,包含24个主流平台,目前在GitHub上已经表星11.8k了。Github链接:https://github.com/Kr1s77/awesome-python-login-model
▍已完成的主流网站
上面是作者已经完成的一些主流网站了,其中有的是通过 selenium登录,有的是通过 抓包直接模拟登录,有的是利用scrapy框架。这个很容易理解,因为有的网站设计比较复杂,通过抓包很难实现模拟登录,这样用 selenium+webdriver 就会相对轻松一些。虽然在登录的时候采用的是selenium,为了效率,我们可以在登录过后得到的cookie维护起来,然后调用requests或者scrapy等进行数据采集,这样数据采集的速度可以得到保证。
▍模拟登录GitHub
这里boy哥给大家展示一个模拟登录GitHub的代码。
"""
github第二种登录方式
info:
author:CriseLYJ
github:https://github.com/CriseLYJ/
update_time:2019-3-7
"""import re
import requests
from lxml import etreeclass Login(object):
class GithubLogin(object):def __init__(self, email, password):# 初始化信息self.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36','Referer': 'https://github.com/','Host': 'github.com'}self.session = requests.Session()self.login_url = 'https://github.com/login'self.post_url = 'https://github.com/session'self.session = requests.Session()self.email = emailself.password = password# 模拟登录def login_GitHub(self):# 登录入口post_data = {'commit': 'Sign in','utf8': '✓','authenticity_token': self.get_token(),'login': self.email,'password': self.password}resp = self.session.post(self.post_url, data=post_data, headers=self.headers)print('StatusCode:', resp.status_code)if resp.status_code != 200:print('Login Fail')match = re.search(r'"user-login" content="(.*?)"', resp.text)user_name = match.group(1)print('UserName:', user_name)response = self.session.post(self.post_url, data=post_data, headers=self.headers)print(response.status_code)print(post_data)if response.status_code == 200:print("登录成功!")else:print("登录失败!")# 获取token信息# Get login tokendef get_token(self):response = self.session.get(self.login_url, headers=self.headers)html = etree.HTML(response.content.decode())token = html.xpath('//input[@name="authenticity_token"]/@value')[0]return tokenif response.status_code != 200:print('Get token fail')return Nonematch = re.search(r'name="authenticity_token" value="(.*?)"', response.text)if not match:print('Get Token Fail')return Nonereturn match.group(1)if __name__ == '__main__':email = input('请输入您的账号: ')password = input('请输入您的密码: ')email = input('Account:')password = input('Password:')login = Login(email, password)login = GithubLogin(email, password)login.login_GitHub()
相信这对初学爬虫的朋友是一个很好的教程。但提示一下,模拟登录的代码随时都有可能失效,因为前端的网页HTML、CSS、JS等结构可能会根据公司业务调整之类的发生变化。所以,重点是掌握了各种技巧,学会这些完全可以自己调试完成登录,那时候你也可以成为 contributor 了!