初识 requests
requests 库的宣言是
HTTP for Humans (给人用的 HTTP 库)
我们首先来验证一下。
在网络编程中,最最基本的任务包含:
- 发送请求
- 登录
- 获取数据
- 解析数据
- 反序列化打印内容
我们以 GitHub 为例,先看一下使用 urllib2 要怎么做。为了把事情弄简单点,我们假设实现已经知道,GET 请求 https://api.github.com/ 返回的内容是个 JSON 格式的数据(实际上通过 content-type 也能判断)。
复制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
import urllib2
import json
gh_url = 'https://api.github.com'
cs_user = 'user'
cs_psw = 'password'
req = urllib2.Request(gh_url)
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, gh_url, cs_user, cs_psw)
auth_manager = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_manager)
urllib2.install_opener(opener)
handler = urllib2.urlopen(req)
if handler.getcode() == requests.codes.ok:
text = handler.read()
d_text = json.loads(text)
for k, v in d_text.items():
print k, v
|
如果运行正确,那么代码应该返回:
复制
1 2 3 4 5 6 7 |
issues_url https://api.github.com/issues
current_user_repositories_url https://api.github.com/user/repos{?type,page,per_page,sort}
rate_limit_url https://api.github.com/rate_limit
repository_url https://api.github.com/repos/{owner}/{repo}
...
user_repositories_url https://api.github.com/users/{user}/repos{?type,page,per_page,sort}
team_url https://api.github.com/teams
|
同样的效果,用 requests 库则有如下代码:
复制
1 2 3 4 5 6 7 8 9 10 11 |
import requests
cs_url = 'https://api.github.com'
cs_user = 'user'
cs_psw = 'password'
r = requests.get(cs_url, auth=(cs_user, cs_psw))
if r.status_code == requests.codes.ok
for k, v in r.json().items():
print k, v
|
溢美之词就不用说了,读到这里的你心里肯定只有一声「卧槽,这才是 Python 该有的样子」。那么,接下来我们看看 requests 都有哪些黑魔法。
安装
最推荐的方式,是直接安装推荐过的 Anaconda。
如果你不想安装 Anaconda,那么建议你使用 pip 安装;只需在命令行下执行:
复制
1 |
pip install requests |
基本用法
requests 的基本用法,呃,真是不能再基本了。最基本的操作,就是以某种 HTTP 方法向远端服务器发送一个请求而已;而 requests 库就是这么做的。
复制
1 2 3 4 5 6 7 8 9 10 |
import requests
cs_url = 'http://httpbin.org'
r = requests.get("%s/%s" % (cs_url, 'get'))
r = requests.post("%s/%s" % (cs_url, 'post'))
r = requests.put("%s/%s" % (cs_url, 'put'))
r = requests.delete("%s/%s" % (cs_url, 'delete'))
r = requests.patch("%s/%s" % (cs_url, 'patch'))
r = requests.options("%s/%s" % (cs_url, 'get'))
|
从语法上看,requests 库设计的非常自然。所谓 requests.get,就是以 GET 方式发送一个 REQUEST,得到一个 Response 类的结果,保存为 r。
你可以在 r 中取得所有你想得到的和 HTTP 有关的信息。下面,我们以 GET 方法为例,依次介绍。
URL 传参 / 获取请求的 URL
如果你经常上网(废话,看到这里的都上过网吧……),一定见过类似下面的链接:
1250




被折叠的 条评论
为什么被折叠?



