属性错误:“模块”对象没有属性“urlopen”;
我正在尝试使用 Python 下载网站的 HTML 源代码,但收到此错误。
Traceback (most recent call last):
File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\DICParser\src\WebDownload.py", line 3, in <module>
file = urllib.urlopen("http://www.python.org")
AttributeError: 'module' object has no attribute 'urlopen'
我正在遵循此处的指南: http://www.boddie.org.uk/python /HTML.html
import urllib
file = urllib.urlopen("http://www.python.org")
s = file.read()
f.close()
#I'm guessing this would output the html source code?
print(s)
我正在使用 Python 3。
I'm trying to use Python to download the HTML source code of a website but I'm receiving this error.
Traceback (most recent call last):
File "C:\Users\Sergio.Tapia\Documents\NetBeansProjects\DICParser\src\WebDownload.py", line 3, in <module>
file = urllib.urlopen("http://www.python.org")
AttributeError: 'module' object has no attribute 'urlopen'
I'm following the guide here: http://www.boddie.org.uk/python/HTML.html
import urllib
file = urllib.urlopen("http://www.python.org")
s = file.read()
f.close()
#I'm guessing this would output the html source code?
print(s)
I'm using Python 3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
可能的方法之一:
One of the possible way to do it:
如果您的代码使用Python 2.x版本,您可以执行以下操作:
顺便说一下,我建议使用另一个名为
requests
的模块,它使用起来更友好。您可以使用pip
安装它,并像这样使用它:If your code uses Python version 2.x, you can do the following:
By the way, I suggest another module called
requests
, which is more friendly to use. You can usepip
install it, and use it like this:使用第三方
six
模块让你的代码在Python2之间兼容和Python3。Use the third-party
six
module to make your code compatible between Python2 and Python3.在使用 urlopen 之前添加此
RequestMethods
Add this
RequestMethods
before using urlopen这适用于 Python 2.x。
对于 Python 3,请查看 docs:
This works in Python 2.x.
For Python 3 look in the docs:
Python 2+3 兼容的解决方案是:
A Python 2+3 compatible solution is:
在 Python v3 中,“urllib.request”本身就是一个模块,因此此处不能使用“urllib”。
In Python v3 the "urllib.request" is a module by itself, therefore "urllib" cannot be used here.
让 'dataX = urllib.urlopen(url).read()' 在 python3 中工作(这是正确的对于 python2) 你必须只改变 2 个小东西。
1: urllib 语句本身(在中间添加 .request):
2: 前面的 import 语句(从 'import urlib' 更改为:
并且它应该在 python3 中工作:)
To get 'dataX = urllib.urlopen(url).read()' working in python3 (this would have been correct for python2) you must just change 2 little things.
1: The urllib statement itself (add the .request in the middle):
2: The import statement preceding it (change from 'import urlib' to:
And it should work in python3 :)
更改两行:
我希望您的问题得到解决。
Change TWO lines:
I hope your problem resolved.
对于 python 3,请尝试这样的操作:
它将把视频下载到当前工作目录
我从这里获得帮助
For python 3, try something like this:
It will download the video to the current working directory
I got help from HERE
python3的解决方案:
Solution for python3: