如果我知道内容将是一个字符串,在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进行换壳的输出。
当前回答
下面是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
其他回答
下面是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
使用强大的urllib3库就足够简单了。
像这样导入:
import urllib3
http = urllib3.PoolManager()
然后提出这样的请求:
response = http.request('GET', 'https://example.com')
print(response.data) # Raw data.
print(response.data.decode('utf-8')) # Text.
print(response.status) # Status code.
print(response.headers['Content-Type']) # Content type.
你也可以添加标题:
response = http.request('GET', 'https://example.com', headers={
'key1': 'value1',
'key2': 'value2'
})
更多信息可以在urllib3文档中找到。
Urllib3比内置的urllib更安全,更容易使用。请求或HTTP模块,是稳定的。
如何也发送头
Python 3:
import urllib.request
contents = urllib.request.urlopen(urllib.request.Request(
"https://api.github.com/repos/cirosantilli/linux-kernel-module-cheat/releases/latest",
headers={"Accept" : 'application/vnd.github.full+json"text/html'}
)).read()
print(contents)
Python 2:
import urllib2
contents = urllib2.urlopen(urllib2.Request(
"https://api.github.com",
headers={"Accept" : 'application/vnd.github.full+json"text/html'}
)).read()
print(contents)
如果你想解决方案与httplib2是联机考虑实例化匿名Http对象
import httplib2
resp, content = httplib2.Http().request("http://example.com/foo/bar")
实际上在Python中,我们可以像从文件一样读取HTTP响应,这里有一个从API读取JSON的例子。
import json
from urllib.request import urlopen
with urlopen(url) as f:
resp = json.load(f)
return resp['some_key']