python模块学习----requests模块
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python模块学习----requests模块相关的知识,希望对你有一定的参考价值。
模块安装:pip install requests
用法讲解:
1、基本的GET请求:
>>> r = requests.get("http://httpbin.org/get") >>> print(r.text)
2、带参数的GET请求:
data = {'name':'test','page':'10'} >>> r = requests.get("http://httpbin.org/get",params=data) >>> print(r.text) "url": "http://httpbin.org/get?name=test&page=10"
3、解析json:
r = requests.get("http://httpbin.org/get") >>> dict1 = r.json() >>> dict1 {'args': {}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.4'}, 'origin': '125.82.191.49', 'url': 'http://httpbin.org/get'}
4、获取二进制数据:
r = requests.get("http://blog.51cto.com/favicon.ico") >>> with open('favicon.ico','wb') as f: f.write(r.content)
5、添加headers:
header = {'User-Agent':'Mozlila/5.0'} >>> r = requests.get("http://httpbin.org/get",headers=header) >>> print(r.text)
6、基本POST请求:
data = {'name':'text','age':'22'} >>> r = requests.post("http://httpbin.org/post",data=data) >>> print(r.text)
响应:reponse属性
reponse.status_code:状态码
reponse.headers:http头部信息
reponse.cookies:
reponse.url:
reponse.history:访问的历史记录
状态码判断:
r = requests.get("http://www.baidu.com") >>> if not r.status_code == 200: exit() else: print(r.text)
高级操作:
1、文件上传:
files = {'file':open('1.jpg','rb')} r = requests.post('http://www.baidu.com',files=files)
2、会话维持:
s = requests.Session() s.get("http://www.baidu.com"
3、证书验证:
r = requests.get('url',cart=('/path/server.crt','/path/key'))
4、代理设置:
proxies = { 'http':'http://127.0.0.1:19324', 'https':'https//127.0.0.1:19542' } >>> r = requests.get('http://www.baidu.com',proxies=proxies) 带验证的代理: proxies = { 'http':'http://user:[email protected]:19452' } r = requests.get('http://www.baidu.com',proxies=proxies) socks代理: 安装模块:pip3 install requests[socks] proxies = { 'http':'socks5://127.0.0.1:1222', 'https':'socks5://127.0.0.1:3222' } >>> r = requests.get('http://www.baidu.com',proxies=proxies)
5、超时设置:
r = requests.get(' = 1)
6、认证设置:
r = requests.get('url',auth=('user','123')) 或者是 from requests.auth import HTTPBasicAuth >>> r = requests.get('url',auth=HTTPBasicAuth('user','123'))
以上是关于python模块学习----requests模块的主要内容,如果未能解决你的问题,请参考以下文章