requests库学习

说明:
requests使用Apache2 licensed 许可证的HTTP库
支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动响应内容的编码,支持国际化的URL和POST数据自动编码。
会自动实现持久连接keep-alive

缺点:无法获取脚本动态生成的信息

请求方法(get post put delete head options):
0 requests.request() #构造一个请求,支撑以下各方法的基础
1 requests.get(‘https://github.com/timeline.json’) # GET请求,主要方法(全部资源)
2 requests.post(“http://httpbin.org/post”) # POST请求,
3 requests.put(“http://httpbin.org/put”) # PUT请求,提交PUT请求,存储
4 requests.delete(“http://httpbin.org/delete”) # DELETE请求,删除
5 requests.head(“http://httpbin.org/get”) # HEAD请求,网页头信息
6 requests.options(“http://httpbin.org/get” ) # OPTIONS请求
7 requests.patch() #提交局部修改请求

发送带参数的get请求:
payload = {'key1':'value1','key2':['value2','value3']} #可以传递list参数
r = requests.get("http://httpbin.org/get",params = payload) #使用params传递参数
print(r.url)

http://httpbin.org/get?key1=value1&key2=value2&key2=value3

requests.request(method,url,kwargs)
method:请求方式
eg:r = requests.request("get",url)
kwargs 控制访问的参数,可选
params 传递参数
data 字典
json json格式
headers 字典,http头定制
cookies
auth
files 字典类型,传输文件
timeout 设定超时时间 s为单位
proxies 字典 设定访问代理服务器,可以增加登陆认证

allow_redirects Ture/False,默认为Ture,重定向开关
stream  Ture/False,默认为Ture,获取内容立即下载开关
Verify  Ture/False,默认为Ture,认证SSL证书开关
cert    本地SSL证书路径

requests.get(url,params=None,kwargs)
requests.head(url,
kwargs)
requests.post(url,data=None,json=None,kwargs)
requests.put(url,data=None,
kwargs)
requests.patch(url,data=None,kwargs)
requests.delete(url,
kwargs)

Response对象的属性:
r.status_code http请求的返回状态码
r.text http响应内容的字符串形式,即url对应的页面内容
r.headers http响应头信息
r.encoding 从http头中猜测的响应内容的编码方式
r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
r.content http响应内容的二进制形式,可以用于下载

...
r.status_code
if 200 -->r.text / r.encoding...
else -->出错/异常

异常:
requests.ConnectionError 网络连接错误异常
requests.HTTPError HTTP错误异常
requests.URLRequired URL缺失
requests.TooManyRedirects 超过最大重定义次数
requests.ConnectTimeout 连接远程服务器超时
requests.Timeout 请求URL超时
r.raise_for_status() 如果不是200,产生requests.HTTPError异常

eg:

def get_HTML(url):  #获取网页源代码
    try:
        r = requests.get(url,timeout=30)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except:
        return "连接失败"

定制请求头:
为请求添加 HTTP 头部,只要简单地传递一个 dict 给 headers 参数就可以了
eg:
url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)
注意: 定制 header 的优先级低于某些特定的信息源,例如:
如果在 .netrc 中设置了用户认证信息,使用 headers= 设置的授权就不会生效。
而如果设置了auth= 参数,.netrc 的设置就无效了。
如果被重定向到别的主机,授权 header 就会被删除。
代理授权 header 会被 URL 中提供的代理身份覆盖掉。
在我们能判断内容长度的情况下,header 的 Content-Length 会被改写
所有的 header 值必须是 string、bytestring 或者 unicode。

猜你喜欢

转载自www.cnblogs.com/jian-h/p/11782341.html