Request的代码实例
先导入模块
import requests.adapters
不同方式获取网页内容, 返回一个Response对象, 请求的参数可以为url或Request对象
r0 = requests.get("https://github.com/timeline.json")
r1 = requests.post("http://httpbin.org/post")
r2 = requests.put("http://httpbin.org/put")
r3 = requests.delete("http://httpbin.org/delete")
r4 = requests.head("http://httpbin.org/get")
r5 = requests.options("http://httpbin.org/get")
r6 = requests.patch("http://httpbin.org/get")
Request对象:
class requests.Request(method=None, url=None, headers=None, files=None, data=None, params=None, auth=None, cookies=None, hooks=None, json=None)
上边所有的获取方式都调用底层的request方法, 所以request方法有的参数, 上边几个函数都应该有:
requests.request(method, url, **kwargs)
kwargs包括: params / data / json / headers / cookies / files / auth / timeout / allow_redirects(bool) / proxies / verify(bool) / stream / cert
Response对象: class requests.Response
包含的主要属性: content / cookies / encoding / headers / history / is_permanent_redirect / is_redirect / reason / status_code / text / url 等
包含的主要方法:
iter_content(chunk_size=1, decode_unicode=False) / iter_lines(chunk_size=512, decode_unicode=None, delimiter=None)
包含的主要方法: close() / json(**kwargs) / raise_for_status() 等
以字典的形式传递URL参数, 也可以直接以?xx=xx&xx=xx的形式将其放在url后
params = {
"key1": "value1", "key2": "value2"}
r = requests.get("http://httpbin.org/get", params=params)
print(r.url) # http://httpbin.org/get?key2=value2&key1=value1
以字典的形式传递URL参数: 字典里带有列表
params = {
"key1": "value1", "key2": ["value2", "value3"]}
r = requests.get("http://httpbin.org/get", params=params)
print(r.url) # http://httpbin.org/get?key1=value1&key2=value2&key2=value3
获取网页内容
r = requests.get("https://github.com/timeline.json")
print(r.text) # 返回正常的网页内容, 即解压解码之后的内容
print(r.content) # 返回byte类型的网页内容, 即值解压, 没有解码
print(r.json()) # 如果网页内容为json, 直接返回一个json对象
print(r.encoding) # 返回网页的编码: "utf-8"
Requests会自动解码来自服务器的内容, 也可以自己更改
r.encoding = "ISO-8859-1"
print(r.text) # 此时使用新的r.encoding解码后的新值