以前咱们用了 urllib 库,这个做为入门的工具仍是不错的,对了解一些爬虫的基本理念,掌握爬虫爬取的流程有所帮助。入门以后,咱们就须要学习一些更加高级的内容和工具来方便咱们的爬取。那么这一节来简单介绍一下 requests 库的基本用法。html
注:Python 版本依然基于 2.7python
如下内容大多来自于官方文档,本文进行了一些修改和总结。要了解更多能够参考git
官方文档github
利用 pip 安装web
1
|
$ pip install requests
|
或者利用 easy_installjson
1
|
$ easy_install requests
|
经过以上两种方法都可以完成安装。api
首先咱们引入一个小例子来感觉一下浏览器
1
2
3
4
5
6
7
8
|
import requests
r = requests.get('http://cuiqingcai.com')
print type(r)
print r.status_code
print r.encoding
#print r.text
print r.cookies
|
以上代码咱们请求了本站点的网址,而后打印出了返回结果的类型,状态码,编码方式,Cookies等内容。服务器
运行结果以下cookie
1
2
3
4
|
<class 'requests.models.Response'>
200
UTF-8
<RequestsCookieJar[]>
|
怎样,是否是很方便。别急,更方便的在后面呢。
requests库提供了http全部的基本请求方式。例如
1
2
3
4
5
|
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")
|
嗯,一句话搞定。
最基本的GET请求能够直接用get方法
1
|
r = requests.get("http://httpbin.org/get")
|
若是想要加参数,能够利用 params 参数
1
2
3
4
5
|
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
print r.url
|
运行结果
1
|
http://httpbin.org/get?key2=value2&key1=value1
|
若是想请求JSON文件,能够利用 json() 方法解析
例如本身写一个JSON文件命名为a.json,内容以下
1
2
3
|
["foo", "bar", {
"foo": "bar"
}]
|
利用以下程序请求并解析
1
2
3
4
5
|
import requests
r = requests.get("a.json")
print r.text
print r.json()
|
运行结果以下,其中一个是直接输出内容,另一个方法是利用 json() 方法解析,感觉下它们的不一样
1
2
3
4
|
["foo", "bar", {
"foo": "bar"
}]
[u'foo', u'bar', {u'foo': u'bar'}]
|
若是想获取来自服务器的原始套接字响应,能够取得 r.raw 。 不过须要在初始请求中设置 stream=True 。
1
2
3
4
5
|
r = requests.get('https://github.com/timeline.json', stream=True)
r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'
|
这样就获取了网页原始套接字内容。
若是想添加 headers,能够传 headers 参数
1
2
3
4
5
6
|
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'content-type': 'application/json'}
r = requests.get("http://httpbin.org/get", params=payload, headers=headers)
print r.url
|
经过headers参数能够增长请求头中的headers信息
对于 POST 请求来讲,咱们通常须要为它增长一些参数。那么最基本的传参方法能够利用 data 这个参数。
1
2
3
4
5
|
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print r.text
|
运行结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
{
"args": {},
"data": "",
"files": {},
"form": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "23",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.9.1"
},
"json": null,
"url": "http://httpbin.org/post"
}
|
能够看到参数传成功了,而后服务器返回了咱们传的数据。
有时候咱们须要传送的信息不是表单形式的,须要咱们传JSON格式的数据过去,因此咱们能够用 json.dumps() 方法把表单数据序列化。
1
2
3
4
5
6
7
|
import json
import requests
url = 'http://httpbin.org/post'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
print r.text
|
运行结果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
{
"args": {},
"data": "{\"some\": \"data\"}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "16",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.9.1"
},
"json": {
"some": "data"
},
"url": "http://httpbin.org/post"
}
|
经过上述方法,咱们能够POST JSON格式的数据
若是想要上传文件,那么直接用 file 参数便可
新建一个 a.txt 的文件,内容写上 Hello World!
1
2
3
4
5
6
|
import requests
url = 'http://httpbin.org/post'
files = {'file': open('test.txt', 'rb')}
r = requests.post(url, files=files)
print r.text
|
能够看到运行结果以下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
{
"args": {},
"data": "",
"files": {
"file": "Hello World!"
},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "156",
"Content-Type": "multipart/form-data; boundary=7d8eb5ff99a04c11bb3e862ce78d7000",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.9.1"
},
"json": null,
"url": "http://httpbin.org/post"
}
|
这样咱们便成功完成了一个文件的上传。
requests 是支持流式上传的,这容许你发送大的数据流或文件而无需先把它们读入内存。要使用流式上传,仅需为你的请求体提供一个类文件对象便可
1
2
|
with open('massive-body') as f:
requests.post('http://some.url/streamed', data=f)
|
这是一个很是实用方便的功能。
若是一个响应中包含了cookie,那么咱们能够利用 cookies 变量来拿到
1
2
3
4
5
6
|
import requests
url = 'http://example.com'
r = requests.get(url)
print r.cookies
print r.cookies['example_cookie_name']
|
以上程序仅是样例,能够用 cookies 变量来获得站点的 cookies
另外能够利用 cookies 变量来向服务器发送 cookies 信息
1
2
3
4
5
6
|
import requests
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
print r.text
|
运行结果
1
|
'{"cookies": {"cookies_are": "working"}}'
|
能够已经成功向服务器发送了 cookies
能够利用 timeout 变量来配置最大请求时间
1
|
requests.get('http://github.com', timeout=0.001)
|
注:timeout 仅对链接过程有效,与响应体的下载无关。
也就是说,这个时间只限制请求的时间。即便返回的 response 包含很大内容,下载须要必定时间,然而这并无什么卵用。
在以上的请求中,每次请求其实都至关于发起了一个新的请求。也就是至关于咱们每一个请求都用了不一样的浏览器单独打开的效果。也就是它并非指的一个会话,即便请求的是同一个网址。好比
1
2
3
4
5
|
import requests
requests.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = requests.get("http://httpbin.org/cookies")
print(r.text)
|
结果是
1
2
3
|
{
"cookies": {}
}
|
很明显,这不在一个会话中,没法获取 cookies,那么在一些站点中,咱们须要保持一个持久的会话怎么办呢?就像用一个浏览器逛淘宝同样,在不一样的选项卡之间跳转,这样其实就是创建了一个长久会话。
解决方案以下
1
2
3
4
5
6
|
import requests
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get("http://httpbin.org/cookies")
print(r.text)
|
在这里咱们请求了两次,一次是设置 cookies,一次是得到 cookies
运行结果
1
2
3
4
5
|
{
"cookies": {
"sessioncookie": "123456789"
}
}
|
发现能够成功获取到 cookies 了,这就是创建一个会话到做用。体会一下。
那么既然会话是一个全局的变量,那么咱们确定能够用来全局的配置了。
1
2
3
4
5
6
|
import requests
s = requests.Session()
s.headers.update({'x-test': 'true'})
r = s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})
print r.text
|
经过 s.headers.update 方法设置了 headers 的变量。而后咱们又在请求中设置了一个 headers,那么会出现什么结果?
很简单,两个变量都传送过去了。
运行结果
1
2
3
4
5
6
7
8
9
10
|
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.9.1",
"X-Test": "true",
"X-Test2": "true"
}
}
|
若是get方法传的headers 一样也是 x-test 呢?
1
|
r = s.get('http://httpbin.org/headers', headers={'x-test': 'true'})
|
嗯,它会覆盖掉全局的配置
1
2
3
4
5
6
7
8
9
|
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.9.1",
"X-Test": "true"
}
}
|
那若是不想要全局配置中的一个变量了呢?很简单,设置为 None 便可
1
|
r = s.get('http://httpbin.org/headers', headers={'x-test': None})
|
运行结果
1
2
3
4
5
6
7
8
|
{
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.9.1"
}
}
|
嗯,以上就是 session 会话的基本用法
如今随处可见 https 开头的网站,Requests能够为HTTPS请求验证SSL证书,就像web浏览器同样。要想检查某个主机的SSL证书,你可使用 verify 参数
如今 12306 证书不是无效的嘛,来测试一下
1
2
3
4
|
import requests
r = requests.get('https://kyfw.12306.cn/otn/', verify=True)
print r.text
|
结果
1
|
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)
|
果然如此
来试下 github 的
1
2
3
4
|
import requests
r = requests.get('https://github.com', verify=True)
print r.text
|
嗯,正常请求,内容我就不输出了。
若是咱们想跳过刚才 12306 的证书验证,把 verify 设置为 False 便可
1
2
3
4
|
import requests
r = requests.get('https://kyfw.12306.cn/otn/', verify=False)
print r.text
|
发现就能够正常请求了。在默认状况下 verify 是 True,因此若是须要的话,须要手动设置下这个变量。
若是须要使用代理,你能够经过为任意请求方法提供 proxies 参数来配置单个请求
1
2
3
4
5
6
7
|
import requests
proxies = {
"https": "http://41.118.132.69:4433"
}
r = requests.post("http://httpbin.org/post", proxies=proxies)
print r.text
|
也能够经过环境变量 HTTP_PROXY 和 HTTPS_PROXY 来配置代理
1
2
|
export HTTP_PROXY="http://10.10.1.10:3128"
export HTTPS_PROXY="http://10.10.1.10:1080"
|
经过以上方式,能够方便地设置代理。
以上讲解了 requests 中最经常使用的参数,若是须要用到更多,请参考官方文档 API
以上总结了一下 requests 的基本用法,若是你对爬虫有了必定的基础,那么确定能够很快上手,在此就很少赘述了。
练习才是王道,你们尽快投注于实践中吧。