Python 导入错误:无法导入名称 urlopen
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38471736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ImportError : cannot import name urlopen
提问by plzhelp
I am trying to open up an URL for my project and here is my code:
我正在尝试为我的项目打开一个 URL,这是我的代码:
from urllib2 import urlopen
page = urlopen("https://docs.python.org/3/howto/urllib2.html")
contents = page.read()
It's just a simple code for a demo however, when I run the codes, I got the following error "ImportError : cannot import name urlopen"
这只是一个简单的演示代码,但是,当我运行代码时,出现以下错误“ImportError : cannot import name urlopen”
I tried to type "pip install urllib2" into CMD and got the following error as well "Could not find a version that satisfies the requirement urllib2...no matching distribution found for urllib2"
我尝试在 CMD 中键入“pip install urllib2”,但也出现以下错误“找不到满足 urllib2 要求的版本...找不到 urllib2 的匹配发行版”
How do I solve this error as I'm using python 2.7.12 instead of python3
我如何解决这个错误,因为我使用的是 python 2.7.12 而不是 python3
回答by dmlicht
I'm going to take an educated guess and assume you are using python3. In python3, urllib2 has been split into urllib.request
and urllib.error
. See note at the top of the urllib2 page. The function you are looking for is contained in urllib.request
. Try the following:
我将进行有根据的猜测,并假设您使用的是 python3。在python3中,urllib2已经被拆分为urllib.request
和urllib.error
。请参阅 urllib2 页面顶部的注释。您要查找的函数包含在urllib.request
. 请尝试以下操作:
from urllib.request import urlopen
page = urlopen("https://docs.python.org/3/howto/urllib2.html")
contents = page.read()
回答by sahutchi
The answer to this question breaks down into two sections. The solution differs based on if you are using python 2 or python 3.
这个问题的答案分为两个部分。解决方案因您使用的是 python 2 还是 python 3 而异。
In python 3 urllib2 is no longer used. Try using urllib.request.
在 python 3 中不再使用 urllib2。尝试使用 urllib.request。
In python 2 you may just have a bad install or old version of urllib2. Try pip install urllib2.
在python 2中,您可能只是安装错误或urllib2的旧版本。尝试 pip install urllib2。