requests是一个很实用的Python HTTP客户端库,编写爬虫和测试服务器响应数据时经常会用到
之前没有记录这个模块的使用方法,现在补充记录下
首先我们安装这个模块
01.pip install requests
然后主要的用法以下几种
post/get请求
01.r = requests.get("http://www.sulao.cn/")
通常,你想要发送一些编码为表单形式的数据—非常像一个HTML表单。 要实现这个,只需简单地传递一个字典给 data 参数。你的数据字典 在发出请求时会自动编码为表单形式
01.param = {
02. key1: value1,03. key2: value204.}05.r = requests.get(", data=param)
我们也可以在header中携带信息进去
01.headers = {
02. "Content-Type": "application/json",03.}04.r = requests.get("http://www.sulao.cn/", data=param, headers=headers)
r.text 返回headers中的编码解析的结果,可以通过r.encoding = 'gbk'来变更解码方式
r.content返回二进制结果
r.json()返回JSON格式,可能抛出异常
r.status_code
r.raw返回原始socket respons,需要加参数stream=True
POST和GET用法基本一样
下载图片
01.r = requests.get("/static/upload/2019/01/201901171547691686645594.jpg")
02.with open("test.jpg", "wb") as f:03. f.write(f.content)
传递文件
01.files = {'file': open('record.log', 'rb')}
02.r = requests.get("http://www.sulao.cn/", files=files)
配置files,filename, content_type and headers
01.files = {'file': ('record.log', open('record.log', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
02.files = {'file': ('record.log', 'some,data,to,send\nanother,row,to,send\n')}
如果是下载大文件需要使用流式方式下载,避免引起较大的内存消耗,例如下载视频
01.with open(os.path.join(download_dir, video_name), 'wb') as video:
02. video_response = requests.get(download_url, headers=headers, stream=True)03. for chunk in video_response.iter_content(chunk_size=1024):04. if chunk:05. video.write(chunk)06. print('视频下载完成')07.
内容版权声明:除非注明,否则皆为本站原创文章。
转载注明出处:https://sulao.cn/post/678
评论列表