如果我知道内容将是一个字符串,在Python中最快的HTTP GET方法是什么?我正在搜索文档中的一个快速一行程序,如:
contents = url.get("http://example.com/foo/bar")
但所有我能找到使用谷歌是httplib和urllib -我无法在这些库中找到一个快捷方式。
标准的Python 2.5是否有类似上述的某种形式的快捷方式,或者我应该写一个url_get函数?
我宁愿不捕获对wget或curl进行换壳的输出。
如果我知道内容将是一个字符串,在Python中最快的HTTP GET方法是什么?我正在搜索文档中的一个快速一行程序,如:
contents = url.get("http://example.com/foo/bar")
但所有我能找到使用谷歌是httplib和urllib -我无法在这些库中找到一个快捷方式。
标准的Python 2.5是否有类似上述的某种形式的快捷方式,或者我应该写一个url_get函数?
我宁愿不捕获对wget或curl进行换壳的输出。
当前回答
使用请求库:
import requests
r = requests.get("http://example.com/foo/bar")
然后你可以这样做:
>>> print(r.status_code)
>>> print(r.headers)
>>> print(r.content) # bytes
>>> print(r.text) # r.content as str
运行如下命令安装请求:
pip install requests
其他回答
Python 3:
import urllib.request
contents = urllib.request.urlopen("http://example.com/foo/bar").read()
Python 2:
import urllib2
contents = urllib2.urlopen("http://example.com/foo/bar").read()
urllib的文档。请求并阅读。
看看httplib2,除了许多非常有用的特性之外,它还提供了您想要的东西。
import httplib2
resp, content = httplib2.Http().request("http://example.com/foo/bar")
其中内容将是响应体(作为字符串),而resp将包含状态和响应标头。
虽然它不包含在标准的python安装中(但它只需要标准的python),但它绝对值得一试。
如果您专门使用HTTP api,还有更方便的选择,如Nap。
例如,以下是如何从2014年5月1日起从Github获得gist:
from nap.url import Url
api = Url('https://api.github.com')
gists = api.join('gists')
response = gists.get(params={'since': '2014-05-01T00:00:00Z'})
print(response.json())
更多例子:https://github.com/kimmobrunfeldt/nap#examples
如果你想解决方案与httplib2是联机考虑实例化匿名Http对象
import httplib2
resp, content = httplib2.Http().request("http://example.com/foo/bar")
下面是Python中的wget脚本:
# From python cookbook, 2nd edition, page 487
import sys, urllib
def reporthook(a, b, c):
print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c),
for url in sys.argv[1:]:
i = url.rfind("/")
file = url[i+1:]
print url, "->", file
urllib.urlretrieve(url, file, reporthook)
print