使用Request登录Gethub

知识点:

1、Cookie

2、Auth_token

 

思路步骤:

第一步, 分析提交认证POST请求需要哪些内容:

在浏览器中任意错误账号登录https://github.com/login

会自动跳转到Session页面

查看提交到session页面:

  Request Headers中的Content-Type: application/x-www-form-urlencoded (application/x-www-form-urlencoded表示requests提交数据时使用data进行封装,application/json表示requests提交数据时使用json进行封装)

  Form Data中的表单信息,其中需要注意的是 authenticity_token, 该token是在https://github.com/login页面中通过get方式获取到

第二步:

在浏览器中访问https://github.com/login

通过登录的Form表单div标签,找到authenticity_token input标签

通过bs4拿到这个input标签的值,让POST登录时带上

 

 

代码示例

import requests
from bs4 import BeautifulSoup as bs


# 第一次GET请求,主要是获取gethub发送Post登录请求所需要的auth_token及Cookie.
response = requests.get("https://github.com/login")
soup = bs(response.text, "html.parser")
auth_token = soup.find(name="input", attrs={"name": "authenticity_token"}).get("value")
response_cookie_dict = response.cookies.get_dict()


# 第二次POST请求,提交Data进行认证,并获取Cookie.
response2 = requests.post("https://github.com/session",
                          data={
                              "commit": "Sign in",
                              "utf8": "",
                              "authenticity_token": auth_token,
                              "login": "xxxx",
                              "password": "xxxx"
                          },
                          cookies=response_cookie_dict)
response2_cookie_dict = response2.cookies.get_dict()

# 将GET和POST获取到的Cookie拼装为一个Cookie.
all_cookie_dict = {}
all_cookie_dict.update(response2_cookie_dict)
all_cookie_dict.update(response_cookie_dict)

# 第三次GET请求,带上前两次的Cookie,并获取登录后的页面信息
response3 = requests.get("https://github.com/settings/profile",
                         cookies=all_cookie_dict)
soup = bs(response3.text, "html.parser")
company = soup.find(name="input", attrs={"id": "user_profile_company"}).get("value")

print("Company:", company)

 

posted @ 2017-10-15 14:12  Vincen_shen  阅读(413)  评论(0)    收藏  举报