python requests
Requests: HTTP for Humans
Behold, the power of Requests:
>>> r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
>>> r.status_code
200
>>> 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, ...}
requests api
requests.get(‘https://github.com/timeline.json’) #GET请求
requests.post(“http://httpbin.org/post”) #POST请求
requests.put(“http://httpbin.org/put”) #PUT请求
requests.delete(“http://httpbin.org/delete”) #DELETE请求
requests.head(“http://httpbin.org/get”) #HEAD请求
requests.options(“http://httpbin.org/get”) #OPTIONS请求
以上的HTTP方法,对于WEB系统一般只支持 GET 和 POST,有一些还支持 HEAD 方法。
1、带参数的请求实例:
import requests
requests.get('http://www.dict.baidu.com/s', params={'wd': 'python'}) #GET参数实例
requests.post('http://www.itwhy.org/wp-comments-post.php', data={'comment': '测试POST'}) #POST参数实例
2、POST发送JSON数据:
import requests import json r = requests.post('https://api.github.com/some/endpoint', data=json.dumps({'some': 'data'})) print(r.json())
3、定制header:
import requests import json data = {'some': 'data'} headers = {'content-type': 'application/json', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'} r = requests.post('https://api.github.com/some/endpoint', data=data, headers=headers) print(r.text)
Response对象
r.status_code #响应状态码
r.raw #返回原始响应体,也就是 urllib 的 response 对象,使用 r.raw.read() 读取
r.content #字节方式的响应体,会自动为你解码 gzip 和 deflate 压缩
r.text #字符串方式的响应体,会自动根据响应头部的字符编码进行解码
r.headers #以字典对象存储服务器响应头,但是这个字典比较特殊,字典键不区分大小写,若键不存在则返回None
#*特殊方法*#
r.json() #Requests中内置的JSON解码器
r.raise_for_status() #失败请求(非200响应)抛出异
response.encoding
def bs_baidu():
url = "https://baike.baidu.com"
response = requests.get(url)
print(response.status_code)
bs_text = response.text
print(bs_text)
执行后出现乱码,
print(response.encoding)
结果:ISO-8859-1
解决方法:增加 response.encoding = 'utf-8'