天天看点

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("填入真实的用户名", "填入真实的密码")