Python之Requests模塊使用詳解

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

一、導入

下載完成後,導入模塊很簡單,代碼如下:

1
import requests

二、請求url

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

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

1
r=requests.get("http://pythontab.com/justTest")

現在,我們得到了一個響應對象r,我們可以利用這個對象得到我們想要的任何信息。

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


2.發送帶參數的get請求

1
2
payload = {'key1''value1''key2''value2'}
= requests.get("http://pythontab.com/justTest", params=payload)

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

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

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

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

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

1
2
3
4
>>> 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請求

1
= requests.post("http://pythontab.com/postTest", data = {"key":"value"})

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

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

1
2
3
4
>>> import json
>>> import requests
>>> payload = {"key":"value"}
>>> r = requests.post("http://pythontab.com/postTest", data = json.dumps(payload))

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

1
2
>>> payload = {"key":"value"}
>>> r = requests.post("http://pythontab.com/postTest", json=payload)

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

1
2
3
4
>>> url = 'http://pythontab.com/postTest'
>>> files = {'file'open('report.xls''rb')}
>>> r = requests.post(url, files=files)
>>> r.text

我們還可以在post文件時指定文件名等額外的信息:

1
2
3
>>> 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發送請求簡單吧!

三、獲取返回信息

下面我們來看下發送請求後如何獲取返回信息。我們繼續使用最上面的例子:

1
2
3
>>> import requests
>>> r=requests.get('http://pythontab.com/justTest')
>>> r.text

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

1
2
>>> r.encoding
'utf-8'

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

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

這樣就把輸出格式改爲“ISO-8859-1”了。

還有一個輸出語句,叫r.content,那麼這個和r.text有什麼區別呢?r.content返回的是字節流,如果我們請求一個圖片地址並且要保存圖片的話,就可以用到,這裏舉個代碼片段如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def saveImage( imgUrl,imgName ="default.jpg" ):
    = 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”的選項,如:

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

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

1
2
3
>>> r = requests.get('http://pythontab.com/justTest')
>>> r.status_code
200

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

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

四、關於headers

我們可以打印出響應頭:

1
2
>>> r= requests.get("http://pythontab.com/justTest")
>>> r.headers

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

1
2
3
4
5
6
7
8
9
{
    'content-encoding''gzip',
    'transfer-encoding''chunked',
    'connection''close',
    'server''nginx/1.0.4',
    'x-runtime''147ms',
    'etag''"e1ca502697e5c9317743dc078f67693a"',
    'content-type''application/json'
}

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

1
r.headers['Content-Type']

或者

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

如果我們想獲得請求頭(也就是我們向服務器發送的頭信息)該怎麼辦呢?可以使用r.request.headers直接獲得。

同時,我們在請求數據時也可以加上自定義的headers(通過headers關鍵字參數傳遞):

1
2
>>> headers = {'user-agent''myagent'}
>>> r= requests.get("http://pythontab.com/justTest",headers=headers)

五、關於Cookies

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

1
2
3
4
>>> url = 'http://www.pythontab.com'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'

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

1
2
3
>>> url = 'http://pythontab.com/cookies'
>>> cookies={'cookies_are':'working'}
>>> r = requests.get(url, cookies=cookies)

六、關於重定向

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

1
2
3
4
5
>>> r = requests.get('http://pythontab.com/')
>>> r.url
'http://pythontab.com/'
>>> r.history
[]

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

1
r = requests.get('http://pythontab.com', allow_redirects=False)

七、關於請求時間

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

1
requests.get('http://pythontab.com', timeout=1)

八、關於代理

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

1
2
3
4
5
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了:

1
2
3
4
5
s=requests.Session()
login_data={'form_email':'[email protected]','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模塊也可以下載網頁,代碼如下:

1
2
3
4
r=requests.get("http://www.pythontab.com")
with open("haha.html","wb") as html:
    html.write(r.content)
html.close()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章