python requests的安裝與簡單運用(轉)


安裝方法1:我在ubuntu下安裝requests的過程(先要安裝pip,pip是linux上快速安裝python包的軟件):

 

Install pip and virtualenv for Ubuntu 10.10 Maverick and newer
 

 

$ sudo apt-get install python-pip python-dev build-essential 

 

$ sudo pip install --upgrade pip 

 

$ sudo pip install --upgrade virtualenv 

 

For older versions of Ubuntu

 

 

 

Install Easy Install

 

$ sudo apt-get install python-setuptools python-dev build-essential 

 

Install pip

 

$ sudo easy_install pip 

 

Install virtualenv

 

$ sudo pip install --upgrade virtualenv 

 

 

 

安裝 mysql拓展包可以:sudo pip install mysql-python

 

安裝其他的包只要pip + 包的名字 就行了 很方便。而且安裝完的mysqlib用起來沒一點問題,

 

pip安裝完成后,至於這里的requests包的安裝,我們把下載好的包放在桌面就行,直接用sudo pip install kennethreitz-requests-v2.4.3-50-g53d0238.tar.gz 

 

 

以下是該包的一些介紹,轉自http://docs.python-requests.org/en/latest/user/install/#install

 


 

 安裝方法2:

pip類似RedHat里面的yum,安裝軟件非常方便。本節詳細介紹pip的安裝、以及使用方法。

1、pip下載安裝

1.1 pip下載

# wget "https://pypi.python.org/packages/source/p/pip/pip-1.5.4.tar.gz#md5=834b2904f92d46aaa333267fb1c922bb" --no-check-certificate

1.2 pip安裝

# tar -xzvf pip-1.5.4.tar.gz
# cd pip-1.5.4
# python setup.py install

2. pip使用詳解

2.1 pip安裝軟件

# pip install SomePackage
  [...]
  Successfully installed SomePackage

2.2 pip查看已安裝的軟件

# pip show --files SomePackage
  Name: SomePackage
  Version: 1.0
  Location: /my/env/lib/pythonx.x/site-packages
  Files:
   ../somepackage/__init__.py
   [...]

2.3 pip檢查哪些軟件需要更新

# pip list --outdated
  SomePackage (Current: 1.0 Latest: 2.0)

2.4 pip升級軟件

# pip install --upgrade SomePackage
  [...]
  Found existing installation: SomePackage 1.0
  Uninstalling SomePackage:
    Successfully uninstalled SomePackage
  Running setup.py install for SomePackage
  Successfully installed SomePackage

2.5 pip卸載軟件

$ pip uninstall SomePackage
  Uninstalling SomePackage:
    /my/env/lib/pythonx.x/site-packages/somepackage
  Proceed (y/n)? y
  Successfully uninstalled SomePackage

3. pip使用實例

3.1 安裝redis

# pip install redis

3.2 卸載redis

# pip uninstall redis
Uninstalling redis:
  /usr/lib/python2.6/site-packages/redis-2.9.1-py2.6.egg-info
.....省略一些內容....
Proceed (y/n)? y
  Successfully uninstalled redis

3.3 查看待更新軟件

pip list --outdate
pygpgme (Current: 0.1 Latest: 0.3)
pycurl (Current: 7.19.0 Latest: 7.19.3.1)
iniparse (Current: 0.3.1 Latest: 0.4)

4. 常見錯誤

4.1 ImportError No module named setuptools
請參考《ImportError No module named setuptools解決

5. pip參數解釋

# pip --help
 
Usage:   
  pip <command> [options]
 
Commands:
  install                     安裝軟件.
  uninstall                   卸載軟件.
  freeze                      按着一定格式輸出已安裝軟件列表
  list                        列出已安裝軟件.
  show                        顯示軟件詳細信息.
  search                      搜索軟件,類似yum里的search.
  wheel                       Build wheels from your requirements.
  zip                         不推薦. Zip individual packages.
  unzip                       不推薦. Unzip individual packages.
  bundle                      不推薦. Create pybundles.
  help                        當前幫助.
 
General Options:
  -h, --help                  顯示幫助.
  -v, --verbose               更多的輸出,最多可以使用3次
  -V, --version               現實版本信息然后退出.
  -q, --quiet                 最少的輸出.
  --log-file <path>           覆蓋的方式記錄verbose錯誤日志,默認文件:/root/.pip/pip.log
  --log <path>                不覆蓋記錄verbose輸出的日志.
  --proxy <proxy>             Specify a proxy in the form [user:passwd@]proxy.server:port.
  --timeout <sec>             連接超時時間 (默認15秒).
  --exists-action <action>    Default action when a path already exists: (s)witch, (i)gnore, (w)ipe, (b)ackup.
  --cert <path>               證書.

6. 結束

安裝使用一目了然,太簡單了。老板再也不要我安裝軟件了。


 

 

強烈推薦!requests官方文檔已有了中文版,請見http://cn.python-requests.org/en/latest/ 。

python requests文檔上的那個龜
requests是python的一個HTTP客戶端庫,跟urllib,urllib2類似,那為什么要用requests而不用urllib2呢?官方文檔中是這樣說明的:

python的標准庫urllib2提供了大部分需要的HTTP功能,但是API太逆天了,一個簡單的功能就需要一大堆代碼。

我也看了下requests的文檔,確實很簡單,適合我這種懶人。下面就是一些簡單指南。

1. 安裝

安裝很簡單,我是win系統,就在這里下載了安裝包(網頁中download the zipball處鏈接),然后$ python setup.py install就裝好了。
當然,有easy_installpip的朋友可以直接使用:easy_install requests或者pip install requests來安裝。
測試:在IDLE中輸入import requests,如果沒提示錯誤,那說明已經安裝成功了!

2. 小試牛刀

>>>import requests >>> r = requests.get('http://www.zhidaow.com') # 發送請求 >>> r.status_code # 返回碼 200 >>> r.headers['content-type'] # 返回頭部信息 'text/html; charset=utf8' >>> r.encoding # 編碼信息 'utf-8' >>> r.text #內容部分(PS,由於編碼問題,建議這里使用r.content) u'<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml"...' ... 

是不是很簡單?比urllib2和urllib簡單直觀的多?!那請接着看快速指南吧。

3. 快速指南

3.1 發送請求

發送請求很簡單的,首先要導入requests模塊:

>>>import requests 

接下來讓我們獲取一個網頁,例如我個人博客的首頁:

>>>r = requests.get('http://www.zhidaow.com') 

接下來,我們就可以使用這個r的各種方法和函數了。
另外,HTTP請求還有很多類型,比如POST,PUT,DELETE,HEAD,OPTIONS。也都可以用同樣的方式實現:

>>> r = requests.post("http://httpbin.org/post") >>> r = requests.put("http://httpbin.org/put") >>> r = requests.delete("http://httpbin.org/delete") >>> r = requests.head("http://httpbin.org/get") >>> r = requests.options("http://httpbin.org/get") 

因為目前我還沒用到這些,所以沒有深入研究。

3.2 在URLs中傳遞參數

有時候我們需要在URL中傳遞參數,比如在采集百度搜索結果時,我們wd參數(搜索詞)和rn參數(搜素結果數量),你可以手工組成URL,requests也提供了一種看起來很NB的方法:

>>> payload = {'wd': '張亞楠', 'rn': '100'} >>> r = requests.get("http://www.baidu.com/s", params=payload) >>> print r.url u'http://www.baidu.com/s?rn=100&wd=%E5%BC%A0%E4%BA%9A%E6%A5%A0' 

上面wd=的亂碼就是“張亞楠”的轉碼形式。(好像參數按照首字母進行了排序。)

3.3 獲取響應內容

可以通過r.text來獲取網頁的內容。

>>> r = requests.get('https://www.zhidaow.com') >>> r.text u'<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml"...' 

文檔里說,requests會自動將內容轉碼。大多數unicode字體都會無縫轉碼。但我在cygwin下使用時老是出現UnicodeEncodeError錯誤,郁悶。倒是在python的IDLE中完全正常。
另外,還可以通過r.content來獲取頁面內容。

>>> r = requests.get('https://www.zhidaow.com') >>> r.content b'<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml"...' 

文檔中說r.content是以字節的方式去顯示,所以在IDLE中以b開頭。但我在cygwin中用起來並沒有,下載網頁正好。所以就替代了urllib2的urllib2.urlopen(url).read()功能。(基本上是我用的最多的一個功能。)

3.4 獲取網頁編碼

可以使用r.encoding來獲取網頁編碼。

>>> r = requests.get('http://www.zhidaow.com') >>> r.encoding 'utf-8' 

當你發送請求時,requests會根據HTTP頭部來猜測網頁編碼,當你使用r.text時,requests就會使用這個編碼。當然你還可以修改requests的編碼形式。

>>> r = requests.get('http://www.zhidaow.com') >>> r.encoding 'utf-8' >>>r.encoding = 'ISO-8859-1' 

像上面的例子,對encoding修改后就直接會用修改后的編碼去獲取網頁內容。

3.5 json

像urllib和urllib2,如果用到json,就要引入新模塊,如jsonsimplejson,但在requests中已經有了內置的函數,r.json()。就拿查詢IP的API來說:

>>>r = requests.get('http://ip.taobao.com/service/getIpInfo.php?ip=122.88.60.28') >>>r.json()['data']['country'] '中國' 

3.6 網頁狀態碼

我們可以用r.status_code來檢查網頁的狀態碼。

>>>r = requests.get('http://www.mengtiankong.com') >>>r.status_code 200 >>>r = requests.get('http://www.mengtiankong.com/123123/') >>>r.status_code 404 >>>r = requests.get('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN') >>>r.url u'http://www.zhidaow.com/ >>>r.status_code 200 

前兩個例子很正常,能正常打開的返回200,不能正常打開的返回404。但第三個就有點奇怪了,那個是百度搜索結果中的302跳轉地址,但狀態碼顯示是200,接下來我用了一招讓他原形畢露:

>>>r.history (<Response [302]>,) 

這里能看出他是使用了302跳轉。也許有人認為這樣可以通過判斷和正則來獲取跳轉的狀態碼了,其實還有個更簡單的方法:

>>>r = requests.get('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN', allow_redirects = False) >>>r.status_code 302 

只要加上一個參數allow_redirects,禁止了跳轉,就直接出現跳轉的狀態碼了,好用吧?我也利用這個在最后一掌做了個簡單的獲取網頁狀態碼的小應用,原理就是這個。

3.7 響應頭內容

可以通過r.headers來獲取響應頭內容。

>>>r = requests.get('http://www.zhidaow.com') >>> r.headers { 'content-encoding': 'gzip', 'transfer-encoding': 'chunked', 'content-type': 'text/html; charset=utf-8'; ... } 

可以看到是以字典的形式返回了全部內容,我們也可以訪問部分內容。

>>> r.headers['Content-Type'] 'text/html; charset=utf-8' >>> r.headers.get('content-type') 'text/html; charset=utf-8' 

3.8 設置超時時間

我們可以通過timeout屬性設置超時時間,一旦超過這個時間還沒獲得響應內容,就會提示錯誤。

>>> requests.get('http://github.com', timeout=0.001) Traceback (most recent call last): File "<stdin>", line 1, in <module> requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001) 

3.9 代理訪問

采集時為避免被封IP,經常會使用代理。requests也有相應的proxies屬性。

import requests proxies = { "http": "http://10.10.1.10:3128", "https": "http://10.10.1.10:1080", } requests.get("http://www.zhidaow.com", proxies=proxies) 

如果代理需要賬戶和密碼,則需這樣:

proxies = { "http": "http://user:pass@10.10.1.10:3128/", } 

3.10 請求頭內容

請求頭內容可以用r.request.headers來獲取。

>>> r.request.headers {'Accept-Encoding': 'identity, deflate, compress, gzip', 'Accept': '*/*', 'User-Agent': 'python-requests/1.2.3 CPython/2.7.3 Windows/XP'} 

3.11 自定義請求頭部

偽裝請求頭部是采集時經常用的,我們可以用這個方法來隱藏:

r = requests.get('http://www.zhidaow.com') print r.request.headers['User-Agent'] #python-requests/1.2.3 CPython/2.7.3 Windows/XP headers = {'User-Agent': 'alexkh'} r = requests.get('http://www.zhidaow.com', headers = headers) print r.request.headers['User-Agent'] #alexkh 

3.12 持久連接keep-alive

requests的keep-alive是基於urllib3,同一會話內的持久連接完全是自動的。同一會話內的所有請求都會自動使用恰當的連接。

也就是說,你無需任何設置,requests會自動實現keep-alive。

4. 簡單應用

4.1 獲取網頁返回碼

def get_status(url): r = requests.get(url, allow_redirects = False) return r.status_code print get_status('http://www.zhidaow.com') #200 print get_status('http://www.zhidaow.com/hi404/') #404 print get_status('http://mengtiankong.com') #301 print get_status('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN') #302 print get_status('http://www.huiya56.com/com8.intre.asp?46981.html') #500 

后記

1、官方文檔
requests的具體安裝過程請看:http://docs.python-requests.org/en/latest/user/install.html#install
requests的官方指南文檔:http://docs.python-requests.org/en/latest/user/quickstart.html
requests的高級指南文檔:http://docs.python-requests.org/en/latest/user/advanced.html#advanced
2、本文內容部分翻譯自官方文檔,部分自己歸納。
3、大多數用的IDLE格式,累死了,下次直接用編輯器格式,這樣更符合我的習慣。
4、還是那句話,有問題留言或email。
5、圖注:requests官方文檔上的一只老鱉。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM