Python爬虫利器一之Requests库的用法
2017-09-17 21:53
363 查看
Python爬虫利器一之Requests库的用法
前言
之前我们用了 urllib 库,这个作为入门的工具还是不错的,对了解一些爬虫的基本理念,掌握爬虫爬取的流程有所帮助。入门之后,我们就需要学习一些更加高级的内容和工具来方便我们的爬取。那么这一节来简单介绍一下 requests 库的基本用法。注:Python 版本依然基于 2.7
官方文档
以下内容大多来自于官方文档,本文进行了一些修改和总结。要了解更多可以参考官方文档
安装
利用 pip 安装1 | $ pip install requests |
1 | $ easy_install requests |
引入
首先我们引入一个小例子来感受一下12345678 | import requests r = requests.get('http://cuiqingcai.com')print type(r)print r.status_codeprint r.encoding#print r.textprint r.cookies |
1 2 3 4 | <class 'requests.models.Response'> 200 UTF-8 <RequestsCookieJar[]> |
基本请求
requests库提供了http所有的基本请求方式。例如12345 | 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请求可以直接用get方法1 | r = requests.get("http://httpbin.org/get") |
12345 | 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文件命名为a.json,内容如下
123 | ["foo", "bar", { "foo": "bar"}] |
1 2 3 4 5 | import requests r = requests.get("a.json") r.text r.json() |
1234 | ["foo", "bar", { "foo": "bar" }] [u'foo', u'bar', {u'foo': u'bar'}] |
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 参数
123456 | 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 |
基本POST请求
对于 POST 请求来说,我们一般需要为它增加一些参数。那么最基本的传参方法可以利用 data 这个参数。1 2 3 4 5 | import requests payload = {'key1': 'value1', 'key2': 'value2'} r = requests.post("http://httpbin.org/post", data=payload) r.text |
12345678910111213141516171819 | { "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"} |
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)) r.text |
1234567891011121314151617 | { "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"} |
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) r.text |
123456789101112131415161718 | { "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"} |
1 2 | with open('massive-body') as f: requests.post('http://some.url/streamed', data=f) |
Cookies
如果一个响应中包含了cookie,那么我们可以利用 cookies 变量来拿到123456 | import requests url = 'http://example.com'r = requests.get(url)print r.cookiesprint r.cookies['example_cookie_name'] |
1 2 3 4 5 6 | import requests url = 'http://httpbin.org/cookies' cookies = dict(cookies_are='working') r = requests.get(url, cookies=cookies) r.text |
1 | '{"cookies": {"cookies_are": "working"}}' |
超时配置
可以利用 timeout 变量来配置最大请求时间1 | requests.get('http://github.com', timeout=0.001) |
也就是说,这个时间只限制请求的时间。即使返回的 response 包含很大内容,下载需要一定时间,然而这并没有什么卵用。
会话对象
在以上的请求中,每次请求其实都相当于发起了一个新的请求。也就是相当于我们每个请求都用了不同的浏览器单独打开的效果。也就是它并不是指的一个会话,即使请求的是同一个网址。比如12345 | 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": {} } |
解决方案如下
123456 | import requests s = requests.Session()s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')r = s.get("http://httpbin.org/cookies")print(r.text) |
1 2 3 4 5 | { "cookies": { "sessioncookie": "123456789" } } |
那么既然会话是一个全局的变量,那么我们肯定可以用来全局的配置了。
123456 | 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 |
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" } } |
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" } } |
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" } } |
SSL证书验证
现在随处可见 https 开头的网站,Requests可以为HTTPS请求验证SSL证书,就像web浏览器一样。要想检查某个主机的SSL证书,你可以使用 verify 参数现在 12306 证书不是无效的嘛,来测试一下
1234 | 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 的
1234 | import requests r = requests.get('https://github.com', verify=True)print r.text |
1 2 3 4 | import requests r = requests.get('https://kyfw.12306.cn/otn/', verify=False) r.text |
代理
如果需要使用代理,你可以通过为任意请求方法提供 proxies 参数来配置单个请求1234567 | import requests proxies = { "https": "http://41.118.132.69:4433"}r = requests.post("http://httpbin.org/post", proxies=proxies)print r.text |
1 2 | export HTTP_PROXY="http://10.10.1.10:3128" export HTTPS_PROXY="http://10.10.1.10:1080" |
API
以上讲解了 requests 中最常用的参数,如果需要用到更多,请参考官方文档 APIAPI
结语
以上总结了一下 requests 的基本用法,如果你对爬虫有了一定的基础,那么肯定可以很快上手,在此就不多赘述了。练习才是王道,大家尽快投注于实践中吧。
转载请注明:静觅 » Python爬虫利器一之Requests库的用法
相关文章推荐
- Python爬虫利器一之Requests库的用法
- Python爬虫利器一之Requests库的用法
- 芝麻HTTP: Python爬虫利器之Requests库的用法
- Python爬虫利器一之Requests库的用法
- Python爬虫利器一之Requests库的用法
- Python爬虫利器之Beautiful Soup的用法
- Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器之PyQuery的用法
- Python爬虫利器二之Beautiful Soup的用法【转过来,乱了,从原网址看】
- Python爬虫利器三之Xpath语法与lxml库的用法
- Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器五之Selenium的用法
- Python爬虫利器二之Beautiful Soup的用法
- 运维学python之爬虫工具篇(一)Requests库的用法
- Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器五之Selenium的用法
- Python爬虫利器二之Beautiful Soup的用法
- Python爬虫利器Beautiful Soup的用法