requests是Python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢?

官方文档中是这样说明的:

python的标准库urllib2提供了大部分需要的HTTP功能,但是API太逆天了,一个简单的功能就需要一大堆代码。

插播个好消息!刚看到requests有了中文翻译版,建议英文不好的看看,内容也比我的博客好多了,
具体链接是:http://cn.python-requests.org/en/latest/(不过是v1.1.0版,另抱歉,之前贴错链接了)。

1. 安装

安装很简单,我是win系统,就在这里下载了安装包(网页中download the zipball处链接),然后$ python setup.py install就装好了。
当然,有easy_install或pip的朋友可以直接使用:easy_install requests或者pip install requests来安装。
至于linux用户,这个页面还有其他安装方法。
测试:在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"...'
...

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': ''}
>>> 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')
#
print get_status('http://www.zhidaow.com/hi404/')
#
print get_status('http://mengtiankong.com')
#
print get_status('http://www.baidu.com/link?url=QeTRFOS7TuUQRppa0wlTJJr6FfIYI1DJprJukx4Qy0XnsDO_s9baoO8u1wvjxgqN')
#
print get_status('http://www.huiya56.com/com8.intre.asp?46981.html')
#

4.2 例子

#!/bin/env python
#-*- encoding=utf8 -*-
import hashlib
import time import requests
import json SCRET = '' # 签名密钥
API_KEY = '' # 签名的key
def post():
headers = {
'User-Agent': 'Web Client/1.0.0',
'Content-Type': 'application/json'
}
data = {}
data['apikey'] = API_KEY
data['timestamp'] = str(time.time())
data['mobile'] = 'xxxx'
# ----- 签名 start -------- #
# to_sign = ''.join(['%s%s' % (each_key, data[each_key]) for each_key in sorted(data.keys())])
# to_sign = SCRET + to_sign + SCRET
# sign = hashlib.md5(to_sign).hexdigest()
# data['sign'] = sign.upper()
   # --------- end -----------#
url = "http://www.xxxxx.com"
body = json.dumps(data, ensure_ascii=False, encoding='utf8').encode('utf8')
r = requests.post(url, data=body, headers=headers)
response = json.loads(r.text)
print json.dumps(response, ensure_ascii=False, encoding='utf8') if __name__ == '__main__':
post()

后记

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官方文档上的一只老鳖。

转载出处:http://www.zhidaow.com/post/python-requests-install-and-brief-introduction

转: python requests的安装与简单运用的更多相关文章

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

    requests是python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢?官方文档中是这样说明的: python的标准库urllib ...

  2. python requests的安装与简单运用

    requests是python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢?官方文档中是这样说明的: python的标准库urllib ...

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

    http://www.cnblogs.com/fightformylife/p/4134986.html http://cn.python-requests.org/zh_CN/latest/ htt ...

  4. Python——requests的安装及入门-贴吧爬虫

    一.windows平台下requests的安装 1.win+R,输入cmd,打开命令行窗口,输入命令:pip install requests ,即可自动安装库成功 2.输入命令:pip list,即 ...

  5. requests的安装与简单运用

    requests是python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢?官方文档中是这样说明的: python的标准库urllib ...

  6. python web py安装与简单使用

    web.py是一个轻量级的python web框架,简单而且功能强大.相对flask和Django,web.py更适合初学者来学习和了解web开发的基础知识.   安装: pip install we ...

  7. [Python]Pip的安装以及简单的使用

    Pip的安装 安装python以后(我的python版本是32位,版本号2.7.10),如果需要安装一些其他的库,一般有两种办法,一种是自己手动去各个库的官网下载,自己安装:另一种方法是安装pip,使 ...

  8. python和tensorflow安装

    一.Python安装 python采用anaconda安装,简单方便,下载python3.6的anaconda  linux64的sh安装文件. 1.bash Anaconda-2.1.0-Linux ...

  9. Python requests 安装与开发

    Requests 是用Python语言编写HTTP客户端库,跟urllib.urllib2类似,基于 urllib,但比 urllib 更加方便,可以节约我们大量的工作,完全满足 HTTP 测试需求, ...

随机推荐

  1. linux 安装软件各种错误集锦及解决方法

    1.最小化安装了centos, 但是使用ifconfig命令时候出现”bash ifconfig command not found” .解决方法:yum -y install net-tools.x ...

  2. CentOS7.3编译hadoop2.7.3源码

    在使用hive或者是kylin时,可以选择文件的压缩格式,但是这个需要有hadoop native库的支持,默认情况下,hadoop官方发布的二进制包中是不包含native库的,所以无法使用一些压缩相 ...

  3. 开关Windows休眠功能

    在windows休眠的时候会把内存里的数据缓存到硬盘的C:/Hiberfil.sys文件,万一断电能够从中恢复状态,然而这对SSD硬盘损耗很大,如果没必要还是关了吧: 关闭: powercfg -h ...

  4. 【Unix网络编程】chapter7套接字选项

    7.1 概述 有很多方法来获取和设置影响套接字的选项: getsockopt和setsockopt函数 fcntl函数 ioctl函数 7.2 getsockopt和setsockopt函数 7.3 ...

  5. SP1812 LCS2 - Longest Common Substring II

    能匹配上子串的节点对它的所有parent都有贡献 在树上转移即可 #include<cstdio> #include<algorithm> #include<cstrin ...

  6. spring boot 自定义视图路径

    boot 自定义访问视图路径 . 配置文件 目录结构 启动类: html页面 访问: 覆盖boot默认路径引用. 如果没有重新配置,则在pom引用模板. 修改配置文件. 注意一定要编译工程

  7. 浮动ip原理及简单实现

    原理:https://blog.csdn.net/readiay/article/details/53538085 简单实现:https://www.cnblogs.com/victorwu/p/70 ...

  8. Loadrunner:win10下Vuser 运行脚本通过,Controller执行用户并发报错

    现象:win7安装LR可以正常使用,将win7升级到win10之后,运行场景之后报错:Error (-81024): LR_VUG: The 'QTWeb' type is not supported ...

  9. 52.纯 CSS 创作一个小球绕着圆环盘旋的动画

    原文地址:https://segmentfault.com/a/1190000015295466 感想:重点在小球绕环转动. HTML code: <div class="contai ...

  10. getent passwd 不能访问到 ldap 的用户

    getent passwd  不能访问到 ldap 的用户,搞了一整个下午! 依然没搞定, 一开始是不知道nslcd 需要启动,另外getent passwd 域, 无有用结果, 换个方式搜索 get ...