爬蟲-request(3)
阿新 • • 發佈:2020-07-10
import requests # GET請求 r = requests.get('http://httpbin.org/get') print(r.status_code, r.reason) print('GET請求', r.text) # 帶引數的GET請求 r = requests.get('http://httpbin.org/get', params={'a': '1', 'b': '2'}) print('帶引數的GET請求', r.json()) #POST請求 r = requests.post('http://httpbin.org/post', data={'a': '1'}) print('POST請求', r.json()) # 自定義headers請求 ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) ' \ 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77' \ ' Safari/537.36' headers = {'User-Agent': ua} r = requests.get('http://httpbin.org/headers', headers=headers) print('自定義headers請求', r.json()) #帶cookies的請求 cookies = dict(userid='123456', token='xxxxxxxxxxxxxxxxxxxx') r = requests.get('http://httpbin.org/cookies', cookies=cookies) print('帶cookies的請求', r.json()) # Basic-auth認證請求 r = requests.get('http://httpbin.org/basic-auth/guye/123456', auth=('guye', '123456')) print('Basic-auth認證請求', r.json())# 主動丟擲狀態碼異常 bad_r = requests.get('http://httpbin.org/status/404') print(bad_r.status_code) bad_r.raise_for_status() #使用requests.Session物件請求 # 建立一個Session物件 s = requests.Session() # session物件會儲存伺服器返回的set-cookies頭資訊裡面的內容 s.get('http://httpbin.org/cookies/set/userid/123456789') s.get('http://httpbin.org/cookies/set/token/xxxxxxxxxxxxxxxxxx') # 下一次請求會將本地所有的cookies資訊自動新增到請求頭資訊裡面 r = s.get('http://httpbin.org/cookies') print('檢查session中的cookies', r.json()) # 在requests中使用代理 print('不使用代理:', requests.get('http://httpbin.org/ip').json()) print('使用代理:', requests.get( 'http://httpbin.org/ip', proxies={'http': 'http://iguye.com:41801'} ).json()) r = requests.get('http://httpbin.org/delay/4', timeout=5) print(r.text)
request&urllib的區別
urlencode不能直接處理unicode物件,所以如果是unicode,需要先編碼,有unicode轉到utf8,舉例: urllib.urlencode (u'bl'.encode('utf-8')) Requests支援HTTP連線保持和連線池,支援使用cookie保持會話,支援檔案上傳,支援自動確定響應內容的編碼,支援國際化的 URL 和 POST 資料自動編碼。 IV. requests不是python自帶的庫,需要另外安裝 easy_install or pip install V. requests缺陷:直接使用不能非同步呼叫,速度慢(from others)。官方的urllib可以替代它。