AttributeError:'模块'对象没有属性'urlopen'

我正在尝试使用Python下载网站的HTML源代码,但我收到此错误。

回溯(最近一次通话最后):
文件“C:\ Users \ Sergio.Tapia \ Documents \ NetBeansProjects \ DICParser \ src \ WebDownload.py”,第3行,在file = urllib.urlopen(“ http://www.python.org ”)AttributeError:'module '对象没有属性'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,感谢您的帮助!

这在Python 2.x中起作用。

对于Python 3看这里:

http://docs.python.org/py3k/library/urllib.request.html?highlight=urllib#urllib.request.urlopen

 import urllib.request with urllib.request.urlopen("http://www.python.org") as url: s = url.read() #I'm guessing this would output the html source code? print(s) 

Python 2 + 3兼容解决scheme是:

 import sys if sys.version_info[0] == 3: from urllib.request import urlopen else: # Not Python 3 - today, it is most likely to be Python 2 # But note that this might need an update when Python 4 # might be around one day from urllib import urlopen # Your code where you can use urlopen with urlopen("http://www.python.org") as url: s = url.read() print(s) 
 import urllib.request as ur s = ur.urlopen("http://www.google.com") sl = s.read() print(sl) 

在Python v3中,“urllib.request”本身就是一个模块,因此“urllib”不能在这里使用。

 import urllib.request as ur filehandler = ur.urlopen ('http://www.google.com') for line in filehandler: print(line.strip()) 

为了得到' dataX = urllib.urlopen (url).read() '在python3中的工作(这对python2来说是正确的),你只需要改变2个小东西。

1:urllib语句本身(在中间添加.request):

 dataX = urllib.request.urlopen(url).read() 

2:它前面的import语句(从“import urlib”更改为:

 import urllib.request 

它应该在python3中工作:)