本文实例讲述了Python Requests库基本用法。分享给大家供大家参考,具体如下:
requests是python的一个http client库,提供了一套简捷的API供开发者使用。下面简单介绍一下其安装和使用。这里是官方文档。
0 安装
pip install requests
1 发送请求
r=requests.get('https://www.baidu.com') print r.status_code,r.text r=requests.post('http://httpbin.org/post') r=requests.put('http://httpbin.org/put') r=requests.delete('http://httpbin.org/delete') r=requests.head('http://httpbin.org/head') r=requests.options('http://httpbin.org/')
2 发送get参数
param={'key1':value1,'key2':value2} r=requests.get('http://www.baidu.com/',params=param)
3 发送post参数
param={'key1':value1,'key2':value2} r=requests.post('http://www.baidu.com/',params=param) #表单格式 r=requests.post('http://www.baidu.com/',json=param) #json格式数据 file= {'file':open('1.txt','rb')} r=reuqest.post('http://httpbin.org/post',files=file)
4 文件下载
with open('1.pic','wb') as pic: for chunk in response.iter_content(size): pic.write(chunk)
5 携带header
header={'key1':value1,'key2':value2} r=requests.get('http://www.baidu.com/',headers=header)
6 携带cookie
cookie={'key1':value1,'key2':value2} r=requests.get('http://www.baidu.com/',cookies=cookie)
7 重定向
默认requests是允许重定向的,并将重定向的历史保存在response.history
数组中
如果不需要重定向,可以通过开关来关闭
r=requests.get('http://www.baidu.com/',allow_redirects=False)
8 使用代理
使用socks代理需要安装三方扩展包
pip install requests[socks]
proxy={ 'http':'http://127.0.0.1:8000', 'https':'https://127.0.0.1:8080' 'http':'socks5://user:pass@127.0.0.1:8132' } r=requests.get('https://www.github.com/',proxies=proxy)
9 设置连接超时
r=requests.get('http://www.baidu.com/',timeout=2.5)
10 ssl证书
证书验证
requests.get('https://kennethreitz.com', verify=True) requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))
如果指定本地证书及密钥,则密钥需要是解密的。
11 requests对象
r.url
r.text
r.headers
12 Response对象
response.request
对应的请求对象
response.raw socket
上直接获得的数据
response.text
根据响应头进行解码的文本数据
response.content
不解码,返回二进制数据
response.json()
对返回数据进行json解码
response.headers
词典形式存储返回的headers
response.cookies
词典形式存储返回的cookies
更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
稳了!魔兽国服回归的3条重磅消息!官宣时间再确认!
昨天有一位朋友在大神群里分享,自己亚服账号被封号之后居然弹出了国服的封号信息对话框。
这里面让他访问的是一个国服的战网网址,com.cn和后面的zh都非常明白地表明这就是国服战网。
而他在复制这个网址并且进行登录之后,确实是网易的网址,也就是我们熟悉的停服之后国服发布的暴雪游戏产品运营到期开放退款的说明。这是一件比较奇怪的事情,因为以前都没有出现这样的情况,现在突然提示跳转到国服战网的网址,是不是说明了简体中文客户端已经开始进行更新了呢?
更新日志
- 《丁当 20首重量级歌曲 Fu Good 下一站天后 2CD》[WAV/分轨][650MB]
- 歌莉雅.2012-My.Voice.Story【环星】【FLAC分轨】
- 群星.1993-一曲成名·青春无悔【飞碟】【WAV+CUE】
- 刘德华.2000-爱无知(金装版)【NEWMELODY】【WAV+CUE】
- 许巍《时光漫步》1CD[FLAC/分轨][804.3MB]
- 群星《2024第一季度百度歌曲排行抖音榜top100》1CD[FLAC/分轨][2.3GB]
- 张柏芝《全新经验》[FLAC/分轨][450MB]
- 唐朝.2008-浪漫骑士【音乐家】【WAV+CUE】
- 张芸京.2016-失败的高歌【泡耳音乐】【WAV+CUE】
- 群星.1991-音乐工厂1·皇后大道东【音乐工厂】【WAV+CUE】
- 群星.1992-音乐工厂2·首都【音乐工厂】【WAV+CUE】
- 群星.1994-音乐工厂3·儿童乐园【音乐工厂】【WAV+CUE】
- 胡鸿钧.2021-ex:CHANGE【星梦娱乐】【WAV+CUE】
- 班得瑞原装进口《第一张新世纪专辑:仙境》1CD[APE/CUE分轨][292.3MB]
- 伍佰《摇滚教父 伍佰黄金精选 2CD》[WAV+CUE][990MB]