原文链接:http://wyb0.com/posts/2016/python-module-requests/
无参数的get请求
import requests
resp = requests.get('http://www.baidu.com',timeout=1) #设置了超时
print resp.text #一般用来输出纯文本
print resp.content #一般用来输出pdf、图片等
有参数的get请求
import requests
url = 'http://10.10.10.10:8080/Lab2.0/Login.action'
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
}
payload = {'aaa':'1111','bbb':'2222'}
resp = requests.get(url,params=payload,headers=header)
print resp.url #得到url
print resp.status_code #得到返回的状态码
print resp.headers #得到html头
print resp.cookies #得到cookie
POST请求
import requests
url1 = 'http://10.10.10.10:8080/Lab2.0/Login.action'
url2 = 'http://10.10.10.10:8080/Lab2.0/student.action'
payload = {
'userid':'1315935xxx',
'password':'xxxxxxx',
'quan':'Student',
}
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
}
resp = requests.post(url1,data=payload,headers=header)
cookie = resp.cookies #保存cookie
resp = requests.get(url2,cookies=cookie) #要加上cookie
print resp.text
使用Session
import requests
url = 'http://10.10.10.10:8080/Lab2.0/Login.action'
proxie = {
'http':'http://127.0.0.1:8080'
}
payload = {
'userid':'1315935xxx',
'password':'xxxxxxx',
'quan':'Student',
}
s = requests.Session() #此后请求时不用再声明cookie
resp = s.post(url,data=payload,proxies=proxie)
# 此时再次请求就不用使用cookie了
resp = s.get('http://10.10.10.10:8080/Lab2.0/student.action')
print resp.text