requests.get("https://www.xxx.com/")
headers = {"Accept-Language": "zh-CN,zh;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Cache-Control": "max-age=0",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Sec-Fetch-Mode": "navigate",
"Content-Type": "application/x-www-form-urlencoded"}
data = {"u": user, "p": password}
response = requests.post("https://www.xxx.com/login/", headers=headers, data=data)
注:关于Content-Type为application/x-www-form-urlencoded类型的请求(Request Body为Form Data类型),data按照json格式组装即可,如以上请求,在谷歌浏览器中看到的请求报文为:u=admin&p=12345,但使用request发送请求时不能按这个文本格式来拼接字符串。
response = requests.post("https://www.xxx.com/login/", allow_redirects=False)
注:若不禁止重定向,则当响应是302时,request会进行重定向,期间可能连续发起多次请求,response为最后一次响应内容,其余响应响应在response的history属性中。
response = requests.post("https://www.xxx.com/login/", allow_redirects=False)
print(response.status_code) # HTTP响应码
print(response.cookies["sessionid"]) # 获取Cookie中的sessionid值
print(response.headers["Location"]) # 获取响应头中的Location属性
print(response.content.decode('utf-8')) # 当响应消息体中包含中文时,需要进行转码