天天看點

python的requests子產品實作登

51cto用python的requests子產品實作登陸示例代碼如下:

-- coding:utf-8 --

import requests

import re

client = requests.session()

agent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36"

header = {

"User-Agent": agent

}

URL = "http://home.51cto.com/index"

def get_xsrf():

#擷取xsrf值

response = client.get(URL, headers=header)

match_obj = re.search('.name="csrf-token" content="(.?)"', response.text)

if match_obj:

return match_obj.group(1)

else:

return ""

def _51cto_login(account, password):

#51cto登入

post_url = URL

post_data = {

"_csrf": get_xsrf(),

"LoginForm[username]": account,

"LoginForm[password]": password,

#雖然抓包分析時post有以下2個參數,但是實際登陸時以下兩個參數可有可無

#"LoginForm[rememberMe]": 0,

#"login-button": "登 錄"

}

response = client.post(post_url, data=post_data, headers=header)

#隻有上面認證通過後,請求以下頁面才可以看到登陸後的結果

response = client.get(URL)

#print response.content

print response.text

_51cto_login("填入真實的使用者名", "填入真實的密碼")