找了一个不带验证码登陆的简单网站(图床001网)做python的模拟登陆入门教程:
第一步
首先打开浏览器,按F12打开开发人员工具 ,切换到network,勾选Preserve log和Disable cache。切换Application,右键clear网站cookie。
然后人工登录一遍
第二步
分析每个步骤,可以得出2点重要信息
- 在访问首页还未登录的时候,服务器就给我们传递了一个名为PHPSESSIONID的cookie。(后台99%是php开发的)。
- 在登录表单中含有一个隐藏域,名为auth_token,在登录的时候需要post过去
第三步
知道这两点注意事项就可以开始撸代码了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| from urllib import request from urllib import error from urllib import parse from http import cookiejar import ssl import re
try: _create_unverified_https_context = ssl._create_unverified_context except AttributeError: pass else: ssl._create_default_https_context = _create_unverified_https_context
if __name__ == '__main__': try: index_url = 'https://www.tuchuang001.com/' user_agent = r'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36' head = {'User-Agnet': user_agent, 'Connection': 'keep-alive'} cookie = cookiejar.CookieJar() cookie_support = request.HTTPCookieProcessor(cookie) opener = request.build_opener(cookie_support) req1 = request.Request(url=index_url, headers=head) response1 = opener.open(req1) html = response1.read().decode('utf-8') reg = r'name="auth_token" value="(.*?)"' auth_token = re.compile(reg) auth_token = re.findall(auth_token, html) login_url = 'https://www.tuchuang001.com/login' Login_Data = {} Login_Data['auth_token'] = auth_token[0] Login_Data['login-subject'] = '你的账号' Login_Data['password'] = '你的密码' loginPostData = parse.urlencode(Login_Data).encode('utf-8') req2 = request.Request(url=login_url, data=loginPostData, headers=head) response2 = opener.open(req2) html2 = response2.read().decode('utf-8') reg = r'<span class="text phone-hide">(.*?)</span>' userName = re.compile(reg) userName = re.findall(userName, html2) print(userName) except error.URLError as e: if hasattr(e, 'code'): print("HTTPError:%d" % e.code) elif hasattr(e, 'reason'): print("URLError:%s" % e.reason)
|
看注释基本能看懂代码了,我这里就不再讲解
希望这篇文章能给你带来知识和乐趣,喜欢博主的文章可以加博主好友哦
有好的文章也可以向博主投稿哦