搜尋
首頁後端開發Python教學Python之Requests模組的使用方法詳解

Python之Requests模組的使用方法詳解

Aug 16, 2017 pm 01:20 PM
pythonrequests實例

Requests模組是一個用於網路存取的模組,其實類似的模組有很多,例如urllib,urllib2,httplib,httplib2,他們基本上都提供相似的功能,那為什麼Requests模組就能夠脫引而出呢?可以打開它的官網看一下,是一個「人類「用的http模組。那麼,它究竟怎樣的人性化呢?相信如果你之前用過urllib之類的模組的話,對比下就會發現它確實很人性化。

一、導入

下載完成後,導入模組很簡單,程式碼如下:

import requests

二、請求url

這裡我們列出最常見的發送get或者post請求的語法。

1.發送無參數的get請求:

r=requests.get("http://php.cn/justTest")

現在,我們得到了一個回應物件r,我們可以利用這個物件來得到我們想要的任何資訊。

上面的範例中,get請求沒有任何參數,那如果請求需要參數怎麼辦呢?

2.發送帶參數的get請求

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://php.cn/justTest", params=payload)

以上得知,我們的get參數是以params關鍵字參數傳遞的。

我們可以列印請求的具體url來看看到底對不對:

>>>print r.url
http://pythontab.com/justTest?key2=value2&key1=value1

可以看到確實訪問了正確的url。

也可以傳遞一個list給一個請求參數:

>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
>>> r = requests.get("http://php.cn/justTest", params=payload)
>>> print r.url
http://pythontab.com/justTest?key1=value1&key2=value2&key2=value3

以上就是get請求的基本形式。

3.發送post請求

r = requests.post("http://php.cn/postTest", data = {"key":"value"})

以上得知,post請求參數是以data關鍵字參數傳遞的。

現在的data參數傳遞的是字典,我們也可以傳遞一個json格式的數據,如下:

>>> import json
>>> import requests
>>> payload = {"key":"value"}
>>> r = requests.post("http://php.cn/postTest", data = json.dumps(payload))

由於發送json格式數據太常見了,所以在Requests模組的高版本中,又加入了json這個關鍵字參數,可以直接傳送json資料給post請求而不用再使用json模組了,請看下:

>>> payload = {"key":"value"}
>>> r = requests.post("http://php.cn/postTest", json=payload)

如果我們想post一個檔案怎麼辦呢?這時候就需要用到files參數了:

>>> url = 'http://php.cn/postTest'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
>>> r.text

我們還可以在post檔案時指定檔案名稱等額外的資訊:

>>> url = 'http://php.cn/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發送請求簡單吧!

三、取得回傳訊息

下面我們來看下發送請求後如何取得回傳訊息。我們繼續使用最上面的範例:

>>> import requests
>>> r=requests.get('http://php.cn/justTest')
>>> r.text

r.text是以什麼編碼格式輸出的呢?

>>> r.encoding
'utf-8'

原來是以utf-8格式輸出的。那如果我想改一下r.text的輸出格式呢?

>>> r.encoding = 'ISO-8859-1'

這樣就把輸出格式改為「ISO-8859-1」了。

還有一個輸出語句,叫r.content,那這個跟r.text有什麼差別呢? r.content回傳的是位元組流,如果我們要求一個圖片位址並且要儲存圖片的話,就可以用到,這裡舉個程式碼片段如下:

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」的選項,如:

r = requests.get('https://api.github.com/events', stream=True)。

我們也可以得到回應狀態碼:

>>> r = requests.get('http://php.cn/justTest')
>>> r.status_code
200

也可以用requests.codes.ok來指稱200這個回傳值:

>>> r.status_code == requests.codes.ok
True

四、關於headers

我們可以列印出回應頭:

>>> r= requests.get("http://php.cn/justTest")
>>> r.headers

#`r .headers`回傳的是一個字典,例如:

{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '147ms',
    'etag': '"e1ca502697e5c9317743dc078f67693a"',
    'content-type': 'application/json'
}

我們可以使用以下方法來取得部分回應頭以做判斷:

r.headers['Content-Type']

r.headers.get('Content-Type')

如果我們想取得請求頭(也就是我們傳送給伺服器的頭資訊)該怎麼辦呢?可以使用r.request.headers直接取得。

同時,我們在請求資料時也可以加上自訂的headers(透過headers關鍵字參數傳遞):

>>> headers = {'user-agent': 'myagent'}
>>> r= requests.get("http://php.cn/justTest",headers=headers)

五、關於Cookies

如果一個回應包含cookies的話,我們可以使用下面方法來得到它們:

>>> url = 'http://www.php.cn'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'

我們也可以發送自己的cookie(使用cookies關鍵字參數):

>>> url = 'http://php.cn/cookies'
>>> cookies={'cookies_are':'working'}
>>> r = requests.get(url, cookies=cookies)

六、關於重定向

有時候我們在請求url時,伺服器會自動把我們的請求重定向,例如github會把我們的http請求重定向為https請求。我們可以使用r.history來查看重定向:

>>> r = requests.get('http://php.cn/')
>>> r.url
'http://php.cn/'
>>> r.history
[]

從上面的例子中可以看到,我們使用http協議訪問,結果在r.url中,打印的卻是https協議。那如果我非要伺服器使用http協議,也就是禁止伺服器自動重定向,該怎麼辦呢?使用allow_redirects 參數:

r = requests.get('http://php.cn', allow_redirects=False)

七、關於請求時間

我們可以使用timeout參數來設定url的請求超時時間(時間單位為秒):

requests.get('http://php.cn', timeout=1)

八、關於代理

我們也可以在程式中指定代理程式來進行http或https存取(使用proxies關鍵字參數),如下:

proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}
requests.get("http://php.cn", proxies=proxies)

九、关于session

我们有时候会有这样的情况,我们需要登录某个网站,然后才能请求相关url,这时就可以用到session了,我们可以先使用网站的登录api进行登录,然后得到session,最后就可以用这个session来请求其他url了:

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模块也可以下载网页,代码如下:

r=requests.get("http://www.php.cn")
with open("haha.html","wb") as html:
    html.write(r.content)
html.close()

以上是Python之Requests模組的使用方法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python的科學計算中如何使用陣列?Python的科學計算中如何使用陣列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何處理同一系統上的不同Python版本?您如何處理同一系統上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通過使用pyenv、venv和Anaconda來管理不同的Python版本。 1)使用pyenv管理多個Python版本:安裝pyenv,設置全局和本地版本。 2)使用venv創建虛擬環境以隔離項目依賴。 3)使用Anaconda管理數據科學項目中的Python版本。 4)保留系統Python用於系統級任務。通過這些工具和策略,你可以有效地管理不同版本的Python,確保項目順利運行。

與標準Python陣列相比,使用Numpy數組的一些優點是什麼?與標準Python陣列相比,使用Numpy數組的一些優點是什麼?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基於基於duetoc的iMplation,2)2)他們的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函數函數函數函數構成和穩定性構成和穩定性的操作,製造

陣列的同質性質如何影響性能?陣列的同質性質如何影響性能?Apr 25, 2025 am 12:13 AM

數組的同質性對性能的影響是雙重的:1)同質性允許編譯器優化內存訪問,提高性能;2)但限制了類型多樣性,可能導致效率低下。總之,選擇合適的數據結構至關重要。

編寫可執行python腳本的最佳實踐是什麼?編寫可執行python腳本的最佳實踐是什麼?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy數組與使用數組模塊創建的數組有何不同?Numpy數組與使用數組模塊創建的數組有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,內存效率段

Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Numpy數組的使用與使用Python中的數組模塊陣列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模塊與Python中的數組有何關係?CTYPES模塊與Python中的數組有何關係?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器