會話對象具有requests API的所有方法.
>>> import requests
>>> s = requests.Session()
>>> s.get("http://httpbin.org/cookies/set/sessioncookie/123456789")
<Response [200]>
>>> r = s.get("http://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"})
>>> s.get('http://httpbin.org/headers', headers={
'x-test2': 'true'})
<Response [200]>
# 此時x-test 和x-test2 都會被放入請求頭中
傳遞給請求方法的字典都會與已設置的會話層數據合並. 方法層的參數覆蓋會話的參數. 方法級別的參數不會被跨請求保持
>>> s = requests.Session()
>>> r = s.get('http://httpbin.org/cookies', cookies={
'from-my': 'browser'})
>>> r.text
'{\n "cookies": {\n "from-my": "browser"\n }\n}\n'
>>> r = s.get('http://httpbin.org/cookies')
>>> r.text
'{\n "cookies": {}\n}\n'
>>>
with requests.Session() as s:
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
# 若是在測試環境中, 不知道將來用get post,可以這麼寫
with requests.Session() as s:
resp = s.request(method="get|post", url=url)
# 不知道返回值是什麼的情況下,可以通過content_type來判斷返回值類型
content_type = ["application/json", "application/stream", "text/explain"]
未完待續…