**作者:1world0x00**(說明:在入選本教程的時候,我進行了適當從新編輯)
requests是一個用于在程序中進行http協議下的get和post請求的庫。
## 安裝
~~~
easy_install requests
~~~
或者用
~~~
pip install requests
~~~
安裝好之后,在交互模式下運行:
~~~
>>> import requests
>>> dir(requests)
['ConnectionError', 'HTTPError', 'NullHandler', 'PreparedRequest', 'Request', 'RequestException', 'Response', 'Session', 'Timeout', 'TooManyRedirects', 'URLRequired', '__author__', '__build__', '__builtins__', '__copyright__', '__doc__', '__file__', '__license__', '__name__', '__package__', '__path__', '__title__', '__version__', 'adapters', 'api', 'auth', 'certs', 'codes', 'compat', 'cookies', 'delete', 'exceptions', 'get', 'head', 'hooks', 'logging', 'models', 'options', 'packages', 'patch', 'post', 'put', 'request', 'session', 'sessions', 'status_codes', 'structures', 'utils']
~~~
從上面的列表中可以看出,在http中常用到的get,cookies,post等都赫然在目。
## get請求
~~~
>>> r = requests.get("http://www.itdiffer.com")
~~~
得到一個請求的實例,然后:
~~~
>>> r.cookies
<<class 'requests.cookies.RequestsCookieJar'>[]>
~~~
這個網站對客戶端沒有寫任何cookies內容。換一個看看:
~~~
>>> r = requests.get("http://www.1world0x00.com")
>>> r.cookies
<<class 'requests.cookies.RequestsCookieJar'>[Cookie(version=0, name='PHPSESSID', value='buqj70k7f9rrg51emsvatveda2', port=None, port_specified=False, domain='www.1world0x00.com', domain_specified=False, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False)]>
~~~
原來這樣呀。繼續,還有別的屬性可以看看。
~~~
>>> r.headers
{'x-powered-by': 'PHP/5.3.3', 'transfer-encoding': 'chunked', 'set-cookie': 'PHPSESSID=buqj70k7f9rrg51emsvatveda2; path=/', 'expires': 'Thu, 19 Nov 1981 08:52:00 GMT', 'keep-alive': 'timeout=15, max=500', 'server': 'Apache/2.2.15 (CentOS)', 'connection': 'Keep-Alive', 'pragma': 'no-cache', 'cache-control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 'date': 'Mon, 10 Nov 2014 01:39:03 GMT', 'content-type': 'text/html; charset=UTF-8', 'x-pingback': 'http://www.1world0x00.com/index.php/action/xmlrpc'}
>>> r.encoding
'UTF-8'
>>> r.status_code
200
~~~
下面這個比較長,是網頁的內容,僅僅截取顯示部分:
~~~
>>> print r.text
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>1world0x00sec</title>
<link rel="stylesheet" href="http://www.1world0x00.com/usr/themes/default/style.min.css">
<link rel="canonical" href="http://www.1world0x00.com/" />
<link rel="stylesheet" type="text/css" href="http://www.1world0x00.com/usr/plugins/CodeBox/css/codebox.css" />
<meta name="description" content="愛生活,愛拉芳。不裝逼還能做朋友。" />
<meta name="keywords" content="php" />
<link rel="pingback" href="http://www.1world0x00.com/index.php/action/xmlrpc" />
......
~~~
請求發出后,requests會基于http頭部對相應的編碼做出有根據的推測,當你訪問r.text之時,requests會使用其推測的文本編碼。你可以找出requests使用了什么編碼,并且能夠使用r.coding屬性來改變它。
~~~
>>> r.content
'\xef\xbb\xbf\xef\xbb\xbf<!DOCTYPE html>\n<html lang="zh-CN">\n <head>\n <meta charset="utf-8">\n <meta name="viewport" content="width=device-width, initial-scale=1.0">\n <title>1world0x00sec</title>\n <link rel="stylesheet" href="http://www.1world0x00.com/usr/themes/default/style.min.css">\n <link ......
以二進制的方式打開服務器并返回數據。
~~~
## post請求
requests發送post請求,通常你會想要發送一些編碼為表單的數據——非常像一個html表單。要實現這個,只需要簡單地傳遞一個字典給data參數。你的數據字典在發出請求時會自動編碼為表單形式。
~~~
>>> import requests
>>> payload = {"key1":"value1","key2":"value2"}
>>> r = requests.post("http://httpbin.org/post")
>>> r1 = requests.post("http://httpbin.org/post", data=payload)
~~~
r沒有加data的請求,看看效果:
[](https://camo.githubusercontent.com/80c036d0c0e5842c8c30677cfbb00129edc0d400/687474703a2f2f777870696374757265732e71696e6975646e2e636f6d2f726571756574732d706f7374312e6a7067)
r1是加了data的請求,看效果:
[](https://camo.githubusercontent.com/1da3cca06274c00f49f1cbacbb9b7372ff1e4220/687474703a2f2f777870696374757265732e71696e6975646e2e636f6d2f726571756574732d706f7374322e6a7067)
多了form項。喵。
## http頭部
~~~
>>> r.headers['content-type']
'application/json'
~~~
注意,在引號里面的內容,不區分大小寫`'CONTENT-TYPE'`也可以。
還能夠自定義頭部:
~~~
>>> r.headers['content-type'] = 'adad'
>>> r.headers['content-type']
'adad'
~~~
注意,當定制頭部的時候,如果需要定制的項目有很多,需要用到數據類型為字典。
* * *
## 老齊備注
網上有一個更為詳細敘述有關requests模塊的網頁,可以參考:[http://requests-docs-cn.readthedocs.org/zh_CN/latest/index.html](http://requests-docs-cn.readthedocs.org/zh_CN/latest/index.html)
- 第零部分 獨上高樓,望盡天涯路
- 嘮叨一些關于Python的事情
- 為什么要開設本欄目
- 第一部分 積小流,至江海
- Python環境安裝
- 集成開發環境(IDE)
- 數的類型和四則運算
- 啰嗦的除法
- 開始真正編程
- 初識永遠強大的函數
- 玩轉字符串(1):基本概念、字符轉義、字符串連接、變量與字符串關系
- 玩轉字符串(2)
- 玩轉字符串(3)
- 眼花繚亂的運算符
- 從if開始語句的征程
- 一個免費的實驗室
- 有容乃大的list(1)
- 有容乃大的list(2)
- 有容乃大的list(3)
- 有容乃大的list(4)
- list和str比較
- 畫圈還不簡單嗎
- 再深點,更懂list
- 字典,你還記得嗎?
- 字典的操作方法
- 有點簡約的元組
- 一二三,集合了
- 集合的關系
- Python數據類型總結
- 深入變量和引用對象
- 賦值,簡單也不簡單
- 坑爹的字符編碼
- 做一個小游戲
- 不要紅頭文件(1): open, write, close
- 不要紅頭文件(2): os.stat, closed, mode, read, readlines, readline
- 第二部分 窮千里目,上一層樓
- 正規地說一句話
- print能干的事情
- 從格式化表達式到方法
- 復習if語句
- 用while來循環
- 難以想象的for
- 關于循環的小伎倆
- 讓人歡喜讓人憂的迭代
- 大話題小函數(1)
- 大話題小函數(2)
- python文檔
- 重回函數
- 變量和參數
- 總結參數的傳遞
- 傳說中的函數條規
- 關于類的基本認識
- 編寫類之一創建實例
- 編寫類之二方法
- 編寫類之三子類
- 編寫類之四再論繼承
- 命名空間
- 類的細節
- Import 模塊
- 模塊的加載
- 私有和專有
- 折騰一下目錄: os.path.<attribute>
- 第三部分 昨夜西風,亭臺誰登
- 網站的結構:網站組成、MySQL數據庫的安裝和配置、MySQL的運行
- 通過Python連接數據庫:安裝python-MySQLdb,連接MySQL
- 用Pyton操作數據庫(1):建立連接和游標,并insert and commit
- 用Python操作數據庫(2)
- 用Python操作數據庫(3)
- python開發框架:框架介紹、Tornado安裝
- Hello,第一個網頁分析:tornado網站的基本結構剖析:improt模塊、RequestHandler, HTTPServer, Application, IOLoop
- 實例分析get和post:get()通過URL得到數據和post()通過get_argument()獲取數據
- 問候世界:利用GAE建立tornado框架網站
- 使用表單和模板:tornado模板self.render和模板變量傳遞
- 模板中的語法:tornado模板中的for,if,set等語法
- 靜態文件以及一個項目框架
- 模板轉義
- 第四部分 暮然回首,燈火闌珊處
- requests庫
- 比較json/dictionary的庫
- defaultdict 模塊和 namedtuple 模塊
- 第五部分 Python備忘錄
- 基本的(字面量)值
- 運算符
- 常用的內建函數
- 擴展閱讀(來自網絡文章)
- 人生苦短,我用Python