目录
安装
pip install requests
使用
发送get请求
import requests
if __name__ == '__main__':
# 发送get请求 --带参数
# 等同于直接访问https://httpbin.org/get?kevin=hello
requests.get('https://httpbin.org/get', params={'kevin': 'hello'})
# 当访问接口发生301跳转时,可以设置允许或者禁止跳转
requests.get('http://github.com/', allow_redirects=False)
# 发送get请求, 加proxy
proxies = {'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080'}
requests.get('https://httpbin.org/get', proxies=proxies)
# 发送get请求,加鉴权 -- Basic Auth
# 首先导入HTTPBasicAuth,一般导入语句写在py文件的最前面。
from requests.auth import HTTPBasicAuth
requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'password'))
# 发送get请求,加鉴权 -- Digest Auth
# 首先导入HTTPDigestAuth,一般导入语句写在py文件的最前面。
from requests.auth import HTTPDigestAuth
requests.get('https://api.github.com/user', auth=HTTPDigestAuth('user', 'password'))
# OAuth 1 Authentication
# 首先安装requests_oauthlib (可通过pip install)
from requests_oauthlib import OAuth1
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET', 'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')
requests.get(url, auth=auth)
发送post 请求
import requests
if __name__ == '__main__':
url = 'https://httpbin.org/anything'
headers = {'user-agent': 'my-app/ 0.0.1'}
payloads = {'iTesting': 'better to follow'}
auth = {"username":"iTesting", "password": "Kevin"}
# 直接post
r = requests.post(url, data=payloads)
# post带header
r = requests.post(url, headers=headers, data=payloads)
# post带鉴权, auth类型跟get请求支持的auth类型相同。
r = requests.post(url, headers=headers, data=payloads, auth=HTTPBasicAuth('user', 'password'))
发送put请求
import requests
if __name__ == '__main__':
# 直接发送put请求
# 如需要加header,auth,即参考post请求
r = requests.put('https://httpbin.org/put', data={'hello': 'iTesting'})
print(r.text)
发送delete请求
import requests
if __name__ == '__main__':
# 直接发送delete请求
r = requests.delete('https://httpbin.org/anything', data={'hello': 'iTesting'})
print(r.text)
获取接口返回值
# -*- coding: utf-8 -*-
import requests
if __name__ == "__main__":
s = requests.session()
r = s.post('https://httpbin.org/anything', data={'hello': 'kevin'})
# 返回文本型response
print(r.text)
# #返回文本型response,并用utf-8格式编码
# # 当你用r.text得出的结果是不可读的内容例如包括类似xu'\xe1'或者有错误提示“'ascii' codec can't encode characters in position”时,可以用encode
print(r.text.encode('utf-8'))
# # 获取二进制返回值
print(r.content)
# # 获取请求返回码
print(r.status_code)
# 获取response的headers
print(r.headers)
# 获取请求返回的cookies
s.get('http://google.com')
print(request.cookies.get_dict())
cookie 的保持requests.Session()
import requests
if __name__ == '__main__':
# 初始化一个session对象
s = requests.Session()
# 第一个get,先设置一个session
# httpbin这个网站允许我们通过如下方式设置,在set后写你需要的值即可
s.get('https://httpbin.org/cookies/set/sessioncookie/iTestingIsGood')
# 设置好后获取所有的cookies
r = s.get('https://httpbin.org/cookies')
# 打印,确定我们的cookies被保存了
print(r.text)
# 结果如下
# '{"cookies": {"sessioncookie": "iTestingIsGood"}}'
# -*- coding: utf-8 -*-
import requests
if __name__ == "__main__":
url = 'https://gate.lagou.com/v1/entry/message/newMessageList'
cookie = {'cookie': '_gid=GA1.2.438589688.1601450871; gate_login_token=475844a837230240e1e73e4ecfa34102e65fa8e5384801cca67bbe983a142abb;'}
headers = {'x-l-req-header': '{deviceType: 9}'}
s = requests.Session()
# 直接带登录态发送请求
r = s.get(url, cookies=cookie, headers=headers)
# 不经过登录,也能访问登录后才能访问的接口
print(r.text.encode('utf-8'))
# {"state":1,"message":"成功","content":{"newMessageList":[],"newMessageCount":0}}