AttributeError:“module”对象没有属性“urlopen”

2024-05-01 22:01:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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。


Tags: orghttpmost源代码网站htmlwww错误
3条回答
import urllib.request as ur
s = ur.urlopen("http://www.google.com")
sl = s.read()
print(sl)

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

与Python2+3兼容的解决方案是:

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)

这在Python2.x中有效

对于Python 3,请查看docs

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)

相关问题 更多 >