接着第一章内容继续总结 request 的使用,还是使用 Jupyter 格式记录的,需要实战的从 github 下载原文件执行。
import requests
r = requests.get('https://httpbin.org/get')
r.status_code
requests 还有一个等同的内建对象
r.status_code == requests.codes.ok
r.headers
r.headers.get('content-type')
r.headers['Content-Type']
r = requests.get('http://github.com/')
r.history
### 通过设置allow_redirects参数可以设置跳转,默认为false
r = requests.get('http://github.com/', allow_redirects=False)
r.status_code
requests.get('https://github.com/', timeout=0.001)
import requests
s = requests.Session()
s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('https://httpbin.org/cookies')
r.text
'{\n "cookies": {\n "sessioncookie": "123456789"\n }\n}\n'
s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})
# 'x-test' 和 'x-test2' 都会被提交
r=s.get('https://httpbin.org/headers', headers={'x-test2': 'true'})
r.text
s = requests.Session()
r = s.get('https://httpbin.org/cookies', cookies={'from-my': 'browser'})
print(r.text)
r = s.get('https://httpbin.org/cookies')
r.text
下面这个 session 将会随着 with 这个代码块结束而结束
with requests.Session() as s:
s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
from requests import Request, Session
s = Session()
payload = {'key1': 'value1', 'key2': 'value2'}
req = Request('POST',"https://httpbin.org/post", data=payload)
# 获取预置参数
prepped = req.prepare()
# do something with prepped.body
prepped.body = 'No, I want exactly this as the body.'
# do something with prepped.headers
del prepped.headers['Content-Type']
resp = s.send(prepped,
timeout=10
)
resp.status_code
200
#需要填入一个无效证书的URL,则会抛出异常
r=requests.get('https://example')
requests.get('https://github.com', verify='/path/to/certfile')
requests.get('https://kennethreitz.org', verify=False)
/usr/local/lib/python3.7/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
InsecureRequestWarning)
requests.get('https://kennethreitz.org', cert=('/path/client.cert', '/path/client.key'))
requests.get('https://kennethreitz.org', cert='/wrong_path/client.pem')
with open('massive-body', 'rb') as f:
requests.post('http://some.url/streamed', data=f)
# 方法定义,一个打印url的钩子函数
def print_url(r, *args, **kwargs):
print(r.url)
# 使用钩子
requests.get('https://httpbin.org/', hooks={'response': print_url})
def record_hook(r, *args, **kwargs):
r.hook_called = True
return r
r = requests.get('https://httpbin.org/', hooks={'response': [print_url, record_hook]})
r.hook_called
True