• 生活就是这样,需要去灌溉!
    • 谢谢您的关注,欢迎您的注册与写作!
    • 循环往复,生生不息,或许这就是生命的意义吧!生命是插曲的产品吧!
    • 古今多少事,都付笑言中!
    • 风住尘香花已尽,日晚倦梳头。物是人非事事休,欲语泪先流。
    • 闻说双溪春尚好,也拟泛轻舟,只恐双溪舴艋舟,载不动许多愁。

python requests的安装与简单运用

Linux 柳叶扉鸿 6年前 (2018-10-18) 803次浏览 已收录 扫描二维码
内容纲要

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

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

我也看了下 requests 的文档,确实很简单,适合我这种懒人。下面就是一些简单指南。

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

1. 安装

安装很简单,我是 win 系统,就在这里下载了安装包(网页中 download the zipball 处链接),然后$ python setup.py install就装好了。
当然,有easy_installpip的朋友可以直接使用: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"...' ...

是不是很简单?比 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 官方文档上的一只老鳖。

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

原文始发于:python requests 的安装与简单运用


柳叶扉鸿 , 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明python requests的安装与简单运用
相关文章 相关文章 相关文章
喜欢 (0)