Python3.x:requests的用法
1,requests 比 urllib.request 容错能力更强;
2,通常用法:
(1).认证、状态码、header、编码、json
r = requests.get(‘https://api.github.com/user‘, auth=(‘user‘, ‘pass‘)) r.status_code r.headers[‘content-type‘] 输出:‘application/json; charset=utf8‘ r.encoding 输出:‘utf-8‘ r.text 输出:u‘{"type":"User"...‘ r.json() 输出:{u‘private_gists‘: 419, u‘total_private_repos‘: 77, ...}
(2).发起请求
import requests URL="http://www.bsdmap.com/" # r = requests.get(URL) # r = requests.post(URL) # r = requests.put(URL) # r = requests.delete(URL) # r = requests.head(URL) # r = requests.options(URL)
(3).通过URL传递参数
payload = {‘key1‘: ‘value1‘, ‘key2‘: ‘value2‘} r = requests.get("http://httpbin.org/get", params=payload) print r.url 输出:u‘http://httpbin.org/get?key2=value2&key1=value1‘
(4).返回内容
import requests r = requests.get(‘https://github.com/timeline.json‘) r.text 输出:‘[{"repository":{"open_issues":0,"url":"https://github.com/... r.encoding 输出:‘utf-8‘ r.encoding = ‘ISO-8859-1‘
(5).二进制内容
r.content 输出:b‘[{"repository":{"open_issues":0,"url":"https://github.com/... from PIL import Image from StringIO import StringIO i = Image.open(StringIO(r.content))
(6).JSON
import requests r = requests.get(‘https://github.com/timeline.json‘) r.json() 输出:[{u‘repository‘: {u‘open_issues‘: 0, u‘url‘: ‘https://github.com/...
(7).超时
requests.get(‘http://github.com‘, timeout=0.001)
(8).自定义header
import json url = ‘https://api.github.com/some/endpoint‘ payload = {‘some‘: ‘data‘} headers = {‘content-type‘: ‘application/json‘} r = requests.post(url, data=json.dumps(payload), headers=headers)
官方文档:http://docs.python-requests.org/en/latest/user/quickstart/
原文地址:https://www.cnblogs.com/lizm166/p/8150854.html
时间: 2024-10-09 11:43:35