067 Python語法之Requests庫

總體介紹

  1. 由于原生urllib不好用,所以作者寫了這個庫

庫的地址

  1. http://docs.python-requests.org/en/master

學(xué)好Requests的意義

  1. 這是一個網(wǎng)絡(luò)時代
  2. 爬蟲的利器
  3. 服務(wù)器編程基礎(chǔ)(Restful API)
  4. 自動化測試接口(Python + Requests)

環(huán)境準(zhǔn)備

  1. http://httpbin.org/
  2. pip install gunicorn httpbin
  3. 使用gunicorn httpbin:app,可以在本地訪問這個網(wǎng)址

Http基本原理

Request

  1. GET/HTTP/1.1
  2. Start Line:請求方法,請求地址,請求協(xié)議
  3. Host:www.baidu.com
  4. User-Agent:Curl/7.43.0
  5. Accept:/

Response

  1. 200 OK Start Line(狀態(tài)碼)
  2. Headers

簡單小程序

  1. urllib,urllib2是獨(dú)立的關(guān)系和模塊
  2. Requests庫使用了urllib3(多次請求重復(fù)利用一個socket)

1. 使用urllib

import urllib
import urllib.request
import urllib.response

response = urllib.request.urlopen("http://httpbin.org/")
print(response.info())          # header
print(response.getheaders())    # 鍵值對形式的header
print(response.getcode())       # code
print(response.read().decode("utf-8"))  # 網(wǎng)頁數(shù)據(jù)

2. 使用Requests

import requests

response = requests.get("http://httpbin.org/ip")
print(response.headers)     # header鍵值對形式
print(response.status_code) # 狀態(tài)碼
print(response.text)        # 網(wǎng)頁數(shù)據(jù)
print(response.json())      # Json數(shù)據(jù)
print(type(response.json()))      # Json數(shù)據(jù),字典類型

發(fā)送請求(Request)

請求方法

  1. GET:查看資源
  2. POST:增加一個資源
  3. PUT:創(chuàng)建一個已知資源,對原有資源進(jìn)行修改
  4. PACTH:對已知資源進(jìn)行局部更新(對put的補(bǔ)充)
  5. DELETE:刪除資源
  6. HEAD:查看響應(yīng)頭
  7. OPTIONS:查看可用請求方法

帶參數(shù)的請求

  1. requests.get(url,params={"key1":"value1"})
  2. requests.post(url,data={"key1":"value1","key2":"value2"})
  3. requests.post(url,json={"key1":"value1","key2":"value2"})

請求異常處理(exceptions包中的異常)

  1. BaseHTTPError
  2. ...

自定義Requests

from requests import Request, Session
s = Session()   # 初始化一個Session
headers = {"User-Agent":"fake1.3.4"}    # 自定義頭部
req = Request("GET",url,auth=(username,pwd),headers=headers)    # 定義一個請求
prepped = req.prepare() # 請求準(zhǔn)備

response = s.send(prepped,timeout=5)   # 用Session發(fā)送,請求超時時間5秒

接收響應(yīng)(Response)

Http狀態(tài)碼

  1. 1XX:消息
  2. 2XX:請求成功
  3. 3XX:重定向
  4. 4XX:客戶端錯誤
  5. 5XX:服務(wù)器錯誤

屬性

  1. status_code:回應(yīng)碼
  2. reason:回應(yīng)狀態(tài)(OK)
  3. headers:頭部
  4. url:請求地址
  5. elapsed:請求耗時
  6. request:請求對象
  7. encoding:編碼信息
  8. raw:原始對象
  9. content:bytes類型內(nèi)容
  10. text:解碼過了
  11. json:獲取json信息

下載圖片/文件

headers = {"User-Agent":"瀏覽器信息"}
url = "網(wǎng)址"
response=requests.get(url, headers=headers, stream=True)
from contextlib import closing
with closing(requests.get(url,headers=headers,stream=True)) as response:
    # 打開文件
    with open("demo1.jpg","wb") as fd:
        # 每128字節(jié)寫入一次
        for chunk in response.iter_content(128):
            fd.write(chunk)

事件鉤子

import requests

def get_key_info(response,*args,**kwargs):
    """回調(diào)函數(shù)
    """
    print(response.headers["Content-Type"])

requests.get(url, hooks=dict(response=get_key_info))

進(jìn)階Cookie,Session

HTTP認(rèn)證

requests.get(url, auth=(username,pwd))  # 基本認(rèn)證AUTH

OAUTH認(rèn)證

headers = {"Authorization":"token 具體的token"}
response = requests.get(url,headers = headers)
print(response.request.headers)



import requests

class GithubAuth(AuthBase):
    def __init__(self, token):
        self.token = token
    
    def __call__(self, r):
        r.headers["Authorization"] = " ".join(["token", self.token])
        return r

def auth_advanced():
    auth = GIthubAuth(token具體信息)
    response = requests.get(url,auth=auth)
    print(response.text)

oauth_advanced()

Proxy代理(中介)

  1. 啟動代理服務(wù)Heroku
  2. 在主機(jī)1080端口啟動Socket服務(wù)
  3. 將請求轉(zhuǎn)發(fā)到1080端口
  4. 獲取響應(yīng)的資源
  5. pip install "requests[socketv5]"
  6. Requirement already satisfied(要求已經(jīng)支持)
  7. proxy={'http':'socks5://127.0.0.1:1080'}
  8. result = requests.get(url, proxies=proxy, timeout=10)

Cookie,Session

  1. Session是服務(wù)器端用于保留一些信息的機(jī)制
  2. Cookie是瀏覽器端用于保留信息的一些機(jī)制
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容