如果我知道内容将是一个字符串,在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 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)
其他回答
真是诡异啊
要使它与python 3一起工作,请进行以下更改
import sys, urllib.request
def reporthook(a, b, c):
print ("% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c))
sys.stdout.flush()
for url in sys.argv[1:]:
i = url.rfind("/")
file = url[i+1:]
print (url, "->", file)
urllib.request.urlretrieve(url, file, reporthook)
print
此外,您输入的URL前面应该加上一个“http://”,否则将返回一个未知的URL类型错误。
没有进一步的必要导入,这个解决方案工作(对我来说)-也与https:
try:
import urllib2 as urlreq # Python 2.x
except:
import urllib.request as urlreq # Python 3.x
req = urlreq.Request("http://example.com/foo/bar")
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36')
urlreq.urlopen(req).read()
当没有在头信息中指定“User-Agent”时,我经常很难获取内容。然后通常用类似urllib2的代码取消请求。HTTP错误403:禁止或urllib.error.HTTPError: HTTP错误403:禁止。
对于python >= 3.6,你可以使用dload:
import dload
t = dload.text(url)
json:
j = dload.json(url)
安装: PIP安装负载
如果你想解决方案与httplib2是联机考虑实例化匿名Http对象
import httplib2
resp, content = httplib2.Http().request("http://example.com/foo/bar")
使用请求库:
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