0

This code will not work

import urllib

def loadHtml (url):
    response = urllib.open(url)
    html = response.read()
    return html

firstUrl = 'http://www.google.it';
html = loadHtml (firstUrl);

This is the error

File "af1.py", line 10, in <module>
    html = loadHtml (firstUrl);
File "af1.py", line 5, in loadHtml
    response = urllib.open(url)

I'm at my second day on python .. what's the problem now ?

AttributeError: 'module' object has no attribute 'open'

EDIT: I've not searched for open in urllib because I was not understanding what Python mean by 'module'

4

5 回答 5

5

也许urllib.urlopen()是你需要的,不是urllib.open()吗?

您可以在库中找到更多文档:

于 2013-04-24T14:18:19.667 回答
2

问题正如它所说的那样,urllib没有一个名为open().

也许你的意思是urllib.urlopen()

在不离开 Python 的情况下解决此类问题的一种方法是使用dir()模块上的函数,并使用一些简单的代码来搜索列表:

>>> import urllib
>>> [x  for x in dir(urllib) if x.find("open") >= 0]
['FancyURLopener', 'URLopener', '_urlopener', 'urlopen']
于 2013-04-24T14:18:37.507 回答
2

错误是该urllib模块没有名为open.

>>> 'open' in dir(urllib)
False

请参阅以下片段,了解如何了解模块包含的内容。

>>> import urllib
>>> dir(urllib)
['ContentTooShortError', 'FancyURLopener', 'MAXFTPCACHE', 'URLopener', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__version__', '_ftperrors', '_have_ssl', '_hexdig', '_hextochr', '_hostprog', '_is_unicode', '_localhost', '_noheaders', '_nportprog', '_passwdprog', '_portprog', '_queryprog', '_safe_map', '_safe_quoters', '_tagprog', '_thishost', '_typeprog', '_urlopener', '_userprog', '_valueprog', 'addbase', 'addclosehook', 'addinfo', 'addinfourl', 'always_safe', 'base64', 'basejoin', 'c', 'ftpcache', 'ftperrors', 'ftpwrapper', 'getproxies', 'getproxies_environment', 'getproxies_registry', 'i', 'localhost', 'noheaders', 'os', 'pathname2url', 'proxy_bypass', 'proxy_bypass_environment', 'proxy_bypass_registry', 'quote', 'quote_plus', 'reporthook', 'socket', 'splitattr', 'splithost', 'splitnport', 'splitpasswd', 'splitport', 'splitquery', 'splittag', 'splittype', 'splituser', 'splitvalue', 'ssl', 'string', 'sys', 'test1', 'thishost', 'time', 'toBytes', 'unquote', 'unquote_plus', 'unwrap', 'url2pathname', 'urlcleanup', 'urlencode', 'urlopen', 'urlretrieve']

你的意思是urllib.urlopen

于 2013-04-24T14:19:32.753 回答
1

错误原因:

urllib.open()

也许你想做:

urllib.urlopen()

要看到:

>>> dir(urllib).index('open')

Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    dir(urllib).index('open')
ValueError: 'open' is not in list
于 2013-04-24T14:19:58.490 回答
1

@realtebo 有很多适合初学者的教程。您应该真正从基础开始,而不是尝试使用库。在这里查看

于 2013-04-24T15:20:39.997 回答