爬虫之登录流程

一 先获取登录页面

   拿到authenticity_token
1 请求的url:https://github.com/login
2 请求方法:GET
3 请求头:User-Agent

r1 = requests.get('https://github.com/login',
             headers={
                 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
             },
             )
authenticity_token = re.findall('name="authenticity_token".*?value="(.*?)"', r1.text, re.S)[0]
r1_cookies=r1.cookies.get_dict()
print(authenticity_token)
print(r1_cookies)
模拟浏览器get请求

二 提交表单数据完成登陆

1 请求的url:https://github.com/session
2 请求方法:POST
3 请求头:
Referer:https://github.com/
User-Agent
4 请求体
commit:Sign in
utf8:✓
authenticity_token:pFLyO9choCgUd6mm1AMP7BoeEQ613TRDe49MBREZ7EU7MKM7IELFgmyGfcKXS0hsaIiGJ8YlkTD5nwwV4tebig==
login:378533872@qq.com
password:alex3714

r2 = requests.post('https://github.com/session',
                   headers={
                       "Referer": "https://github.com/",
                       'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
                   },
                   cookies=r1_cookies,
                   data={
                       "commit": "Sign in",
                       'utf8': "",
                       "authenticity_token": authenticity_token,
                       "login": "317828332@qq.com",
                       "password": "alex3714",
                   },
                   allow_redirects=False
                   )

# print(r2.status_code)
# print(r2.history)
模拟浏览器post请求

 三 思路流程

1 get请求需要注意的:请求的url,方法,请求头User-Agent,authenticity_token,还有没有授权的空字典cookies

2 post请求需要注意的:请求的url,方法,请求头(跳转前路径)Referer、User-Agent,请求体(data),还有已授权的字典cookies

3 浏览器发出请求给服务器,服务器返回登录页面 在验证登录的过程中 浏览器发送post请求 (信息包含有请求的url,方法,请求头User-Agent,authenticity_token,还有没有授权的空字典cookies)  服务器

  验证通过后 返回页面(信息包含 请求的url,方法,请求头(跳转前路径)Referer、User-Agent,请求体,还有已授权的字典cookies)

ps:模拟浏览器登录时 注意authenticity_token,和未授权的cookies(re模块里自带cookies),allow_redirects=False(设定跳转与否)

 

posted @ 2018-01-20 15:16  East~L  阅读(554)  评论(0)    收藏  举报