requests模塊詳解

 
Requests 是使用 Apache2 Licensed 許可證的 基於Python開發的HTTP 庫,其在Python內置模塊的基礎上進行了高度的封裝,從而使得Pythoner進行網絡請求時,能夠垂手可得的完成瀏覽器可有的任何操做。
 
 
1.get請求
import requests
url = 'https://www.baidu.com/'
 
# 不帶參數
response = requests.get(url)
print(response.url)    # https://www.baidu.com/
 
# 帶參數
data = {
    'key1': 'value1',
    'key2': 'value2'
}
response = requests.get(url, params=data)
print(response.url)    # https://www.baidu.com/?key1=value1&key2=value2
 
2.post請求
import requests
url = 'https://www.baidu.com/'
data = {
    'key1': 'value1',
    'key2': 'value2'
}
 
# 帶參數
response = requests.post(url, data=data)
print(response.url)    # https://www.baidu.com/
 
# 發送json數據
import json
headers = {'content-type': 'application/json'}
response = requests.post(url, data=json.dumps(data), headers=headers)
 
3.其餘請求
requests.get(url, params=None, **kwargs)
requests.post(url, data=None, json=None, **kwargs)
requests.put(url, data=None, **kwargs)
requests.head(url, **kwargs)
requests.delete(url, **kwargs)
requests.patch(url, data=None, **kwargs)
requests.option(url, **kwargs)
 
# 以上方法是基於此方法構建
requests.request(method, url, **kwargs)
# requests.request(method='get', url)
 
4.其餘參數
###### 1.headers ######
 
headers = {
    'user-agent': '...',
    'content-type': 'application/json'
    ...
}
requests.post(url, headers=headers)
 
 
###### 2.cookies ######
 
cookies = {'c1': 'v1'}
requests.post(url, cookies=cookies)
 
# 也能夠使用CookieJar(字典形式的cookies就是在此基礎上進行的封裝)
from http.cookiejar import CookieJar
from http.cookiejar import Cookie
 
obj = CookieJar()
obj.set_cookie(Cookie(
    version=0, name='user', value='pwd', port=None,
    domain='', path='/', secure=False, expires=None,
  discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False,
  port_specified=False, domain_specified=False, domain_initial_dot=False, path_specified=False)
)
requests.post(url, data={'c1': 'v1'}, cookies=obj)
 
 
###### 3.params ######
 
# 能夠是字典;能夠是字符串;也能夠是字節
requests.get(url, params={'k1': 'v1', 'k2': 'v2'})
requests.get(url, params='k1=v1&k2=v2')
requests.get(url, params=bytes('k1=v1&k2=v2', encoding='utf8'))
 
 
###### 4.data ######
 
# 能夠是字典;能夠是字符串;能夠是字節;能夠是文件對象
requests.post(url, data={'k1': 'v1', 'k2': 'v2'})
requests.post(url, data='k1=v1; k2=v2')
data = 'k1=v1;k2=v2'
requests.post(url, data='k1=v1;k2=v2', headers = {'content-type': 'application/x-www-form-urlencoded'})
requests.post(url, data=open('file.text', 'r', encoding='utf8'))
 
 
###### 5.json ######
 
# 內部進行序列化並做爲請求體發送,自動設置content-type爲aplication/json
requests.post(url, json={'k1': 'v1', 'k2': 'v2'})
 
 
###### 6.post發送文件 ######
 
# 普通發送文件
file_dict = {
    'f1': open('text.txt', 'rb')
}
requests.post(url, files=files_dict)
 
# 自定義文件名1
file_dict = {
    'f1': ('自定義文件名.txt', open('text.txt', 'rb'))
}
requests.post(url, files=files_dict)
 
# 自定義文件名2
file_dict = {
    'f1': ('text.txt', '自定義文件名.txt')
}
requests.post(url, files=files_dict)
 
 
###### 7.auth認證 ######
 
from requests.auth import HTTPBasicAuth, HTTPDigestAuth
requests.get(url, auth=HTTPBasicAuth('user', 'pwd'))
requests.get(url, auth=HTTPDigesAuth('user', 'pwd'))
 
 
###### 8.timeout超時操做 ######
 
# 傳入一個數字:鏈接最大時間
requests.get(url, timeout=1)
 
# 傳入一個元組:鏈接最大時間, 接收數據最大時間
requests.get(url, timeout=(3, 3))
 
 
###### 9.poxies代理 ######
 
# 通常代理(自動檢測http和https,並取得對應的代理
proxies = {
    'http': '127.0.0.1:8888',
    'https': '127.0.0.1:8888'
}
requests.get(url, proxies=proxies)
 
# 專屬代理(指定地址使用專屬代理)
proxies = {'https://www.baidu.com/': 'http': '127.0.0.1:8888'}
requests.get(url, proxies=proxies)
 
# 加密代理
from requests.auth import HTTPProxyAuth
proxies{
    'http': '127.0.0.1:8888',
    'https': '127.0.0.1:8888'
}
auth = HTTPProxyAuth('user', 'pwd')
requests.get(url, proxies=proxies, auth=auth)
 
 
###### 10.stream下載文件 ######
 
# stream = True: 文件一點一點讀取
from contextlib import closing
with closing(requests.get(url, stream=True)) as f:
    for i in f.iter_content():
        print(i)
 
 
###### 11.allow_redirects重定向 ######
 
allow_redirect = False: 不容許重定向
requests.get(url, allow_redirect=False)
 
 
###### 12.session ######
 
# session會自定攜帶cookies和請求頭數據
session = requests.Session()
res = session.get(url)    # 已獲取在此頁面的cookies, 下個請求自動帶此數據
res_2 = session.get(url)    # 在這個url會對cookie進行檢測,只有攜帶第一個cookies才能登錄,使用session能夠自動攜帶
相關文章
相關標籤/搜索