安装并使用python requests发送http请求

Requests是一个Apache2 Licensed HTTP库,使用python编写。旨在设计成为易用的http请求库。意味着你不需要手动添加请求字符串到url,或者对POST数据进行表单编码。

安装Requests

有多种方法来安装requests库,如pip,easy_install和编译安装。
这里推荐pip,如执行:

pip install requests 

导入requests模块

要能够在python使用requests库,必须导入正确的模块。可以在脚本头部添加:

import requests 

发送请求

如获取一个网页的内容

r = request.get(‘https://github.com/timeline.json’)

获取响应状态码

发送请求后,准备往下对网页内容或url进一步处理时,最好先检查一下响应状态码。如下示例:

r = requests.get('https://github.com/timeline.json')
r.status_code
>>200

r.status_code == requests.codes.ok
>>> True

requests.codes['temporary_redirect']
>>> 307

requests.codes.teapot
>>> 418

requests.codes['o/']
>>> 200

获取内容

当web服务器返回响应体后,就可以收集你所需的内容了。

import requests
r = requests.get('https://github.com/timeline.json')
print r.text

# The Requests library also comes with a built-in JSON decoder,
# just in case you have to deal with JSON data

import requests
r = requests.get('https://github.com/timeline.json')
print r.json

查看响应头

通过使用python字典,可以访问和查看服务器的响应头。

r.headers
{
    'status': '200 OK',
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json; charset=utf-8'
}

r.headers['Content-Type']
>>>'application/json; charset=utf-8'

r.headers.get('content-type')
>>>'application/json; charset=utf-8'

r.headers['X-Random']
>>>None

# Get the headers of a given URL
resp = requests.head("http://www.google.com")
print resp.status_code, resp.text, resp.headers

自定义请求头

如果想要添加自定义请求头到一个请求,必须传递一个字典到headers参数。

import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

发送一个POST请求

requests库也可以发送post请求,如下:

r = requests.post(http://httpbin.org/post)

当然也可以发送其它类型的请求,如 PUT, DELETE, HEAD和OPTIONS.

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")

可以使用这些方法完成很多复杂的工作,如使用一个python脚本来创建一个GitHub repo。

import requests, json

github_url = "https://api.github.com/user/repos"
data = json.dumps({'name':'test', 'description':'some test repo'})
r = requests.post(github_url, data, auth=('user', '*****'))

print r.json