python requests的安装与简单运用(转)

安装方法1:我在ubuntu下安装requests的过程(先要安装pip,pip是linux上快速安装python包的软件):php

 

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/#installhtml

 


 

 安装方法2:python

pip相似RedHat里面的yum,安装软件很是方便。本节详细介绍pip的安装、以及使用方法。mysql

一、pip下载安装

1.1 pip下载linux

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

1.2 pip安装git

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

2. pip使用详解

2.1 pip安装软件github

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

2.2 pip查看已安装的软件redis

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

2.3 pip检查哪些软件须要更新sql

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

2.4 pip升级软件json

# 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 

后记

一、官方文档requests的具体安装过程请看:http://docs.python-requests.org/en/latest/user/install.html#installrequests的官方指南文档:http://docs.python-requests.org/en/latest/user/quickstart.htmlrequests的高级指南文档:http://docs.python-requests.org/en/latest/user/advanced.html#advanced二、本文内容部分翻译自官方文档,部分本身概括。三、大多数用的IDLE格式,累死了,下次直接用编辑器格式,这样更符合个人习惯。四、仍是那句话,有问题留言或email。五、图注:requests官方文档上的一只老鳖。

相关文章
相关标签/搜索