<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                [TOC] # Requests庫的基本使用 > `Requests`庫是在`urllib3`庫的基礎上更層次的抽象封裝,使用起來更加簡單,代碼量也會更少。 ## 快速安裝 ``` pip install requests ``` ## 快速編寫示例 > 最好的學習就是從實踐中鍛煉學習,立刻動起小手!從這些簡單示例開始練習。 ### 訪問HTTP協議頁面 ```Python #!/usr/bin/env python3 import requests url = 'https://www.baidu.com' resp = requests.get(url) print(resp.status_code) if resp.status_code == 200: print(resp.text) ``` ### GET-參數查詢信息 下面是兩個`GET`方法參數查詢示例,其中第二個示例的`seen_list`是一個列表,這對于參數名相同并且包含多個值的設置是非常方便的。 ```Python import requests as req payload1 = { 'name': 'Peter', 'age': 23 } payload2 = { 'name': 'Peter', 'seen_list': [1,2,3,4,5,6] } url = 'https://httpbin.org/get' resp = req.get(url, params=payload1) print(resp.url) resp = req.get(url, params=payload2) print(resp.url) ``` 執行結果: ``` $ python ./method_get.py https://httpbin.org/get?name=Peter&age=23 https://httpbin.org/get?name=Peter&seen_list=1&seen_list=2&seen_list=3&seen_list=4&seen_list=5&seen_list=6 ``` ### POST-提交web表單 > `POST`方法通常用于頁面登錄提交表單,因為`POST`提交參數值不會體現在`URL`中,相對更加安全,由于`URL`地址長度是有限制的,`GET`方法無法攜帶大量數據內容,`POST`方法就沒有限制。 ```Python import requests as req payload = { 'name': 'Peter', 'age': 23 } url = 'https://httpbin.org/post' resp = req.post(url, data=payload) print(resp.text) ``` 執行結果: ``` $ python ./method_post.py { "args": {}, "data": "", "files": {}, "form": { "age": "18", "name": "Peter" }, "headers": { "Accept-Encoding": "identity", "Content-Length": "214", "Content-Type": "multipart/form-data; boundary=281e3c05a41e5ec834f98cf2b673113a", "Host": "httpbin.org", "X-Amzn-Trace-Id": "Root=1-5f0c0f9d-f490eb9ad301417e59f7b6a2" }, "json": null, "origin": "127.0.0.1", "url": "https://httpbin.org/post" } ``` 可以看到`form`表單中有了我們`POST`提交的數據了。 ### POST-發送JSON數據 ```Python import requests as req payload = { 'name': 'Peter', 'age': 23 } url = 'https://httpbin.org/post' resp = req.post(url, json=payload) print(resp.text) ``` 執行結果: ``` $ python ./method_post_json.py { "args": {}, "data": "{\"name\": \"Peter\", \"age\": 23}", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "28", "Content-Type": "application/json", "Host": "httpbin.org", "User-Agent": "python-requests/2.24.0", "X-Amzn-Trace-Id": "Root=1-5f0c1120-a6c6b65c1eb9dbdc18e21420" }, "json": { "age": 23, "name": "Peter" }, "origin": "127.0.0.1", "url": "https://httpbin.org/post" } ``` 我們可以看到 `headers`中多了`"Content-Type": "application/json"`字段,省去了`urllib3`設置`headers`的部分了。 ### 使用`stream`流模式下載二進制文件 ```Python import requests as req url = 'https://docs.oracle.com/javase/specs/jls/se14/jls14.pdf' filename = url.split('/')[-1] with req.get(url,stream=True) as r: with open(filename,'wb') as f: f.write(r.content) ``` 當在請求中將stream設為True后,`Requests`無法將連接自動釋放回連接池,需要讀取完所有數據或者手動調用`Requests.close`。 ### 下載一個圖片示例 ```Python import requests as req resp = req.get('http://www.baidu.com/favicon.ico') with open('favicon.ico', 'wb') as f: f.write(resp.content) ``` ### 設置超時`timeout` > 超時判斷分為兩種: Connect建立連接超時 和 Read讀取數據超時 `timeout`超時時間單位為秒, 參數值可以是下面任意一種: - `float`: 最大超時時間,連接和讀數據使用一個。 - `二元組`: (連接超時時間, 讀數據超時時間)。 - `None` : 一直等到地老天荒,海枯石爛。 ```Python #!/usr/bin/env python3 import requests url = 'https://www.baidu.com' try: resp = requests.get(url, timeout = (0.01,3)) print(resp.status_code) if resp.status_code == 200: print(resp.text[:50]) except requests.exceptions.ConnectTimeout as e: print('連接超時: ' + str(e)) ``` ### 訪問HTTPS協議頁面 > `Requests`庫也是使用`certifi`庫進行證書驗證,默認`verify`為`True`,如果設置為`False`也可以訪問,但是會出現SSL的`Warning`警告信息。 ```Python #!/usr/bin/env python3 import requests as req url = 'https://httpbin.org/anything' resp = req.get(url, verify=True) print(resp.status_code) ``` ### 使用代理訪問 ``` import requests as req proxies = { 'http' : '88.198.201.112:8888', 'https' : '88.198.201.112:8888' } print(f'代理地址:{proxies}') resp = req.get('https://httpbin.org/ip', proxies = proxies) print(resp.text) ``` **執行結果:** ```sh $ python proxy_http_get.py 代理地址:{'http': 'http://88.198.201.112:8888', 'https': 'http://88.198.201.112:8888'} { "origin": "88.198.201.112" } ``` 我們訪問的`https`協議地址,代理生效了。 ### SOCKS5協議代理的使用 > 使用前可能需要安裝`PySocks`包才可以使用 ```sh pip install 'requests[socks]' ``` 設置方法同樣簡單如下: ```Python proxies = { 'http': 'socks5://user:pass@host:port', 'https': 'socks5://user:pass@host:port' } ``` 看看這個示例: ```Python import requests as req proxies = { 'http' : 'socks5://127.0.0.1:1080', 'https' : 'socks5://127.0.0.1:1080' } print(f'代理地址:{proxies}') resp = req.get('https://httpbin.org/ip', proxies = proxies) print(resp.text) url = 'https://www.google.com' resp = req.get(url, proxies = proxies) print(f'返回狀態碼:{resp.status_code}') ``` **執行結果:** ```sh $ python ./proxy_socks_get.py 代理地址:{'http': 'socks5://127.0.0.1:1080', 'https': 'socks5://127.0.0.1:1080'} { "origin": "88.198.201.112" } 返回狀態碼:200 ``` ### Session管理 > requests庫的`Session`可以為相同網站的多次訪問保持`cookies`信息,例如模擬登錄操作后,cookies信息會自動保持,繼續訪問該網站其他內容時都會使用這個登錄賬號操作。 ```Python import requests s = requests.Session() s.get('https://httpbin.org/cookies/set/sessioncookie/123456789') r = s.get("https://httpbin.org/cookies") print(r.text) # '{"cookies": {"sessioncookie": "123456789"}}' ``` 如果使用多個代理IP并發訪問同一網站,就不要使用`Session()`,直接使用`get()`或`post()`訪問,否則多個代理IP都會判定為同一個用戶的訪問,這樣就失去了多代理IP并發的作用了。 ## 編碼方式的識別 當你收到一個響應時,Requests 會猜測響應的編碼方式,用于在你調用 Response.text 方法時對響應進行解碼。Requests 首先在 HTTP 頭部檢測是否存在指定的編碼方式,如果不存在,則會使用 charade [http://pypi.python.org/pypi/charade] 來嘗試猜測編碼方式(在Request 2.24.0版本中使用的是`chardet`庫了)。 只有當 HTTP 頭部不存在明確指定的字符集,并且 Content-Type 頭部字段包含 text 值之時, Requests 才不去猜測編碼方式。在這種情況下, RFC 2616 [http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7.1] 指定默認字符集必須是 ISO-8859-1 。Requests 遵從這一規范。如果你需要一種不同的編碼方式,你可以手動設置 Response.encoding 屬性,或使用原始的 Response.content。 ---
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看