关于使用urllib3替换urllib2
问题描述:
我试图使用下面的代码段。我正在使用Python 3,它有urllib3
而不是urllib2。我想知道如何在urllib3
中替换此部分fh = urllib2.urlopen('http://people.ku.edu/~gbohling/geostats/WGTutorial.zip') data = fh.read()
。谢谢。关于使用urllib3替换urllib2
clusterfile = 'ZoneA.dat'
if not os.path.isfile(clusterfile):
fh = urllib2.urlopen('http://people.ku.edu/~gbohling/geostats/WGTutorial.zip')
data = fh.read()
fobj = StringIO.StringIO(data)
myzip = zipfile.ZipFile(fobj,'r')
myzip.extract(clusterfile)
fobj.close()
fh.close()
答
在Python 3 urlopen
是urllib.request
让您有部分修改进口:如果你希望你的脚本在Python 2和Python 3运行,你可以使用
from urllib.request import urlopen
:
try:
from urllib2 import urlopen
except ImportError:
from urllib.request import urlopen
不,urllib3是第三方库。在Python 3中替换urllib2是['urllib.request'](https://docs.python.org/3/library/urllib.request.html#module-urllib.request),你完全可以使用它同样的方式。 –
@Daniel,谢谢。 – user297850