requests基础知识总结

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44846959/article/details/100707669

import requests
###发送请求:
r=requests.get(‘http://api.github.com/events’)
#现在我们相当于有一个名为r的response对象,我们可以从这个对象中获取我们想要的信息
#可以这样发送一个http post请求:
r=requests.post(‘http://httpbin.org/post’,date={‘key’:‘value’})
#其他类型的请求:PUT,DELETE,HEAD,OPTIONS:
r=requests.put(‘http://httpbin.org/put’,data={‘key’:‘value’})
r = requests.delete(‘http://httpbin.org/delete’)
r = requests.head(‘http://httpbin.org/get’)
r = requests.options(‘http://httpbin.org/get’)

###传递URL参数:
#如果想传递 key1=value1 和 key2=value2 到 httpbin.org/get ,那么你可以使用如下代码:
payload={‘key1’:‘value1’,‘key2’:‘value2’}
r=requests.get(“http://httpbin.org/get”,params=payload)
#通过打印输出该url,你能看到url已被正确编码
print(r.url)
#还可以将整个列表作为值传入
paylosd={‘key1’:‘value’,‘key2’:[‘value2’,‘value3’]}
r=requests.get(‘http://httpbin.org/get’,params=payload)

###响应内容:
#我们能读取服务器的响应内容,再次以github为例:
import requests
r = requests.get(‘https://api.github.com/events’)
print(r.text)
#找出requests使用什么编码,并能够使用r.encoding属性来改变它
print(r.encoding)
r.encoding=‘ISO-8859-1’#改变编码方式
print(r.encoding)

###二进制响应内容:
#你可以以字节的方式访问请求响应体,对于非文本请求:
print(r.content)
#requests会自动解码gzip和deflate传输编码的响应数据
#已请求返回的二进制数据创建一张图,你可以使用如下代码(报错,且未解决):
from PIL import Image
from io import BytesIO
import requests
r = requests.get(‘http://httpbin.org/get’)
i=Image.open(BytesIO(r.content))

###JSON响应内容:
#Request中也有一个内置的JSON解码器,助你处理JSON数据
import requests
r=requests.get(‘https://api.github.com/events’)
print(r.json())
print(r.raise_for_status())
#如果json解码失败,r.json()就会抛出一个异常。例如响应内容为401,尝试
#访问r.json()将会抛出ValueError:No JSON object could be decoded异常
#注意:成功调用r.json()并不意味着访问成功,有的服务器会在失败的响应中包含一个
#json对象(比如http 500的错误细节)这种json会被解码返回
#要检查请求是否成功,请使用r.raise_for_status()或者检查r.status_code
#是否和你的期望相同

##原始响应内容:
在罕见的情况下,你可能获取来自服务器的原始套接字响应,那么你可以
访问r.raw 如果确实想这么干,那请你确保在初始请求中设置了stream=True
import requests
r=requests.get(‘http://api.github.com/events’,stream=True)
r.raw
r.raw.read()
#但一般情况下,你应该以下面的模式将文本流保存到文件:
with open(filename,‘wb’)as fd:
for chunk in r.iter_content(chunk_size):
fd.write(chunk)

###定制请求头:
#如果你想添加HTTP头部,只要简单地传递一个dict给headers参数就可以了
#例如,在前面实例中我们没有指定content—type:
url=‘https://api.github.com/some/endpoint’
headers={‘user-agent’:‘my-app/0.0.1’}
r=requests.get(url,headers=headers)

###更加复杂的post请求
#你要发送一些编码为表单形式的数据–非常像一个HTML表单,要实现这个,只需要
#传递一个字典给date参数,你的数据字典在发送请求时会自动编码为表达形式
payload={‘key1’:‘value1’,‘key2’:‘value2’}
r=requests.post(‘http://httpbin.org/post’,data=payload)

###响应状态码,200
import requests
r=requests.get(‘http://httpbin.org/get’)
print(r.status_code)
#为了方便引用,Requests还附带了一个内置的状态码查询对象:
r.status_code==requests.codes.ok
#如果发送了一个错误请求(一个4XX客户端错误,或者5XX服务器错误响应)
#我们可以通过Requsets.raise_for_status()来抛出异常:

###响应头:
#我们可以查看以一个python字典的形式展示的服务器响应头:
r.headers
{
‘content-encoding’: ‘gzip’,
‘transfer-encoding’: ‘chunked’,
‘connection’: ‘close’,
‘server’: ‘nginx/1.0.4’,
‘x-runtime’: ‘148ms’,
‘etag’: ‘“e1ca502697e5c9317743dc078f67693f”’,
‘content-type’: ‘application/json’
}

##Cookie:
如果某个响应中包含一些cookie,你可以快速访问他们:
import requests
url=‘http://example.com/some/cookie/setting/url’
r=requests.get(url)
r.cookies[‘example_cookie_name’]
#要想发送你的cookies到服务器,可以使用cookies参数:
url=‘http://httpbin.org/cookies’
cookies=dict(cookies_are=‘working’)
r=requests.get(url,cookies=cookies)
r.text
print(r.text)
cookies的返回值对象为RequestsCopkieJar,他的行为和字典类似,
#但接口更为完整,适合跨域名,跨路径使用,可以把Cookie jar传到Requests中
import requests
jar=requests.cookies.RequstsCookieJar()
jar.set(‘tasty_cookie’,‘yum’,domain=‘httpbin.org’,path=’/cookies’)
jar.set(‘gross_cookies’,‘blech’,domain=‘httpbin.org’,path=’/elsewhere’)
url=‘http://httpbin.org/cookies’
r=requests.get(url,cookies=jar)
r.text

###重定向与请求历史
##默认情况下,除了HEAD,Requests会自动处理所有的重定向
##可以使用响应对象的history方法来追踪重定向
##Requests.history是一个Response对象的列表,为了完成创建这些对象
##这个对象列表按照从最老到最近的请求进行排序
##例如,GIthub将所有的http请求重定向到https:
#r=requests.get(‘http://github.com’)
#r.url
#r.status_code
#r.history
##如果你使用了HEAD,你也可以启用重定向:
r=requests.head(‘http://github.com’,allow_redirects=True)
#r.url
#r.history

##错误与异常:
遇到网络问题(如:DNS查询失败,拒绝连接等)时,Requests会抛出一个ConnectionError异常
如果HTTP请求返回了不成功的代码,Response.raise_for_statues()会抛出
一个THHPError异常
若请求超时则抛出一个Timeout异常
若请求超过了设定的最大重定向次数,则会抛出一个TooManyRedirects异常
所有Requests显式抛出的异常都继承自requests.exception.RequestExcepyion

猜你喜欢

转载自blog.csdn.net/weixin_44846959/article/details/100707669
今日推荐