<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>

                ThinkChat2.0新版上線,更智能更精彩,支持會話、畫圖、視頻、閱讀、搜索等,送10W Token,即刻開啟你的AI之旅 廣告
                [TOC] Requests模塊是一個用于網絡訪問的模塊 ## 一、導入 下載完成后,導入模塊很簡單,代碼如下: ```python import requests ``` ## 二、請求url 這里我們列出最常見的發送get或者post請求的語法。 ### 1.發送無參數的get請求: ```python r=requests.get("http://pythontab.com/justTest") ``` 現在,我們得到了一個響應對象r,我們可以利用這個對象得到我們想要的任何信息。 上面的例子中,get請求沒有任何參數,那如果請求需要參數怎么辦呢? ### 2.發送帶參數的get請求 ```python payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get("http://pythontab.com/justTest", params=payload) ``` 以上得知,我們的get參數是以params關鍵字參數傳遞的。 我們可以打印請求的具體url來看看到底對不對: ```python >>>print r.url http://pythontab.com/justTest?key2=value2&key1=value1 ``` 可以看到確實訪問了正確的url。 還可以傳遞一個list給一個請求參數: ```python >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']} >>> r = requests.get("http://pythontab.com/justTest", params=payload) >>> print r.url http://pythontab.com/justTest?key1=value1&key2=value2&key2=value3 ``` 以上就是get請求的基本形式。 ## 3.發送post請求 ```python r = requests.post("http://pythontab.com/postTest", data = {"key":"value"}) ``` 以上得知,post請求參數是以data關鍵字參數來傳遞的。 現在的data參數傳遞的是字典,我們也可以傳遞一個json格式的數據,如下: ```python >>> import json >>> import requests >>> payload = {"key":"value"} >>> r = requests.post("http://pythontab.com/postTest", data = json.dumps(payload)) ``` 由于發送json格式數據太常見了,所以在Requests模塊的高版本中,又加入了json這個關鍵字參數,可以直接發送json數據給post請求而不用再使用json模塊了,見下: ```python >>> payload = {"key":"value"} >>> r = requests.post("http://pythontab.com/postTest", json=payload) ``` 如果我們想post一個文件怎么辦呢?這個時候就需要用到files參數了: ```python >>> url = 'http://pythontab.com/postTest' >>> files = {'file': open('report.xls', 'rb')} >>> r = requests.post(url, files=files) >>> r.text ``` 我們還可以在post文件時指定文件名等額外的信息: ```python >>> url = 'http://pythontab.com/postTest' >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})} >>> r = requests.post(url, files=files) ``` tips:強烈建議使用二進制模式打開文件,因為如果以文本文件格式打開時,可能會因為“Content-Length”這個header而出錯。 可以看到,使用Requests發送請求簡單吧! ## 三、獲取返回信息 下面我們來看下發送請求后如何獲取返回信息。我們繼續使用最上面的例子: ```python >>> import requests >>> r=requests.get('http://pythontab.com/justTest') >>> r.text ``` r.text是以什么編碼格式輸出的呢? ```python >>> r.encoding 'utf-8' ``` 原來是以utf-8格式輸出的。那如果我想改一下r.text的輸出格式呢? ```python >>> r.encoding = 'ISO-8859-1' ``` 這樣就把輸出格式改為“ISO-8859-1”了。 還有一個輸出語句,叫r.content,那么這個和r.text有什么區別呢?r.content返回的是字節流,如果我們請求一個圖片地址并且要保存圖片的話,就可以用到,這里舉個代碼片段如下: ```python def saveImage( imgUrl,imgName ="default.jpg" ): r = requests.get(imgUrl, stream=True) image = r.content destDir="D:\" print("保存圖片"+destDir+imgName+"\n") try: with open(destDir+imgName ,"wb") as jpg: jpg.write(image) return except IOError: print("IO Error") return finally: jpg.close ``` 剛才介紹的r.text返回的是字符串,那么,如果請求對應的響應是一個json,那我可不可以直接拿到json格式的數據呢?r.json()就是為這個準備的。 我們還可以拿到服務器返回的原始數據,使用r.raw.read()就可以了。不過,如果你確實要拿到原始返回數據的話,記得在請求時加上“stream=True”的選項,如: ```python r = requests.get('https://api.github.com/events', stream=True)。 ``` 我們也可以得到響應狀態碼: ```python >>> r = requests.get('http://pythontab.com/justTest') >>> r.status_code 200 ``` 也可以用requests.codes.ok來指代200這個返回值: ```python >>> r.status_code == requests.codes.ok True ``` ## 四、關于headers 我們可以打印出響應頭: ```python >>> r= requests.get("http://pythontab.com/justTest") >>> r.headers ``` `r.headers`返回的是一個字典,例如: ```python { 'content-encoding': 'gzip', 'transfer-encoding': 'chunked', 'connection': 'close', 'server': 'nginx/1.0.4', 'x-runtime': '147ms', 'etag': '"e1ca502697e5c9317743dc078f67693a"', 'content-type': 'application/json' } ``` 我們可以使用如下方法來取得部分響應頭以做判斷: ```python r.headers['Content-Type'] ``` 或者 ```python r.headers.get('Content-Type') ``` 如果我們想獲得請求頭(也就是我們向服務器發送的頭信息)該怎么辦呢?可以使用r.request.headers直接獲得。 同時,我們在請求數據時也可以加上自定義的headers(通過headers關鍵字參數傳遞): ```python >>> headers = {'user-agent': 'myagent'} >>> r= requests.get("http://pythontab.com/justTest",headers=headers) ``` ## 五、關于Cookies 如果一個響應包含cookies的話,我們可以使用下面方法來得到它們: ```python >>> url = 'http://www.pythontab.com' >>> r = requests.get(url) >>> r.cookies['example_cookie_name'] 'example_cookie_value' ``` 我們也可以發送自己的cookie(使用cookies關鍵字參數): ```python >>> url = 'http://pythontab.com/cookies' >>> cookies={'cookies_are':'working'} >>> r = requests.get(url, cookies=cookies) ``` ## 六、關于重定向 有時候我們在請求url時,服務器會自動把我們的請求重定向,比如github會把我們的http請求重定向為https請求。我們可以使用r.history來查看重定向: ```python >>> r = requests.get('http://pythontab.com/') >>> r.url 'http://pythontab.com/' >>> r.history [] ``` 從上面的例子中可以看到,我們使用http協議訪問,結果在r.url中,打印的卻是https協議。那如果我非要服務器使用http協議,也就是禁止服務器自動重定向,該怎么辦呢?使用allow_redirects 參數: ```python r = requests.get('http://pythontab.com', allow_redirects=False) ``` ## 七、關于請求時間 我們可以使用timeout參數來設定url的請求超時時間(時間單位為秒): ```python requests.get('http://pythontab.com', timeout=1) ``` ## 八、關于代理 我們也可以在程序中指定代理來進行http或https訪問(使用proxies關鍵字參數),如下: ```python proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.10:1080", } requests.get("http://pythontab.com", proxies=proxies) ``` ## 九、關于session 我們有時候會有這樣的情況,我們需要登錄某個網站,然后才能請求相關url,這時就可以用到session了,我們可以先使用網站的登錄api進行登錄,然后得到session,最后就可以用這個session來請求其他url了: ```python s=requests.Session() login_data={'form_email':'youremail@example.com','form_password':'yourpassword'} s.post("http://pythontab.com/testLogin",login_data) r = s.get('http://pythontab.com/notification/') print r.text ``` 其中,form_email和form_password是豆瓣登錄框的相應元素的name值。 ## 十、下載頁面 使用Requests模塊也可以下載網頁,代碼如下: ```python r=requests.get("http://www.pythontab.com") with open("haha.html","wb") as html: html.write(r.content) html.close() ```
                  <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>

                              哎呀哎呀视频在线观看