Python(新手):如何在我的函数中使用导入的函数?

Python(新手):如何在我的函数中使用导入的函数?,python,urllib,Python,Urllib,此代码将不起作用 import urllib def loadHtml (url): response = urllib.open(url) html = response.read() return html firstUrl = 'http://www.google.it'; html = loadHtml (firstUrl); 这就是错误所在 File "af1.py", line 10, in <module> html = loadH

此代码将不起作用

import urllib

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

firstUrl = 'http://www.google.it';
html = loadHtml (firstUrl);
这就是错误所在

File "af1.py", line 10, in <module>
    html = loadHtml (firstUrl);
File "af1.py", line 5, in loadHtml
    response = urllib.open(url)
编辑:我没有在urllib中搜索open,因为我不理解Python所说的“模块”是什么意思。也许
urllib.urlopen()
是您需要的,而不是
urllib.open()

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

  • 在官方文件中:
  • 或者通过调用
    help(urllib)

问题就如它所说,
urllib
没有名为
open()
的方法

也许你的意思是

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

>>> import urllib
>>> [x  for x in dir(urllib) if x.find("open") >= 0]
['FancyURLopener', 'URLopener', '_urlopener', 'urlopen']

错误在于
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

错误原因:

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
目录(urllib.index('open')) 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 目录(urllib).index('open') ValueError:“打开”不在列表中
@realtebo有很多初学者教程。你真的应该从基础开始,而不是试图跳进图书馆。看看吧

哦,我的天哪,这是个多么愚蠢的问题!谢谢@不客气,哇!我不知道dir方法,有用!!!!!除了
dir()
之外,还有
help()
,它不仅会列出模块的成员(或任何其他对象),还会显示他们的内置帮助(docstrings)。这对于第二天的程序员来说实在太多了!但是它非常有用!
>>> 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