【问题标题】:urllib "module object is not callable"urllib“模块对象不可调用”
【发布时间】:2012-09-28 03:22:57
【问题描述】:

这是我的第三个 python 项目,我收到一条错误消息:'module object' is not callable

我知道这意味着我错误地引用了一个变量或函数。但是反复试验无法帮助我解决这个问题。

import urllib

def get_url(url):
    '''get_url accepts a URL string and return the server response code, response headers, and contents of the file'''
    req_headers = {
        'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.A.B.C Safari/525.13',
        'Referer': 'http://python.org'}

    #errors here on next line
    request = urllib.request(url, headers=req_headers) # create a request object for the URL
    opener = urllib.build_opener() # create an opener object
    response = opener.open(request) # open a connection and receive the http response headers + contents

    code = response.code
    headers = response.headers # headers object
    contents = response.read() # contents of the URL (HTML, javascript, css, img, etc.)
    return code , headers, contents


testURL = get_url('http://www.urlhere.filename.zip')
print ("outputs: %s" % (testURL,))

我一直在使用此链接作为参考: http://docs.python.org/release/3.0.1/library/urllib.request.html

追溯:

Traceback (most recent call last):
  File "C:\Project\LinkCrawl\LinkCrawl.py", line 31, in <module>
    testURL = get_url('http://www.urlhere.filename.zip')
  File "C:\Project\LinkCrawl\LinkCrawl.py", line 21, in get_url
    request = urllib.request(url, headers=req_headers) # create a request object for the URL
TypeError: 'module' object is not callable

【问题讨论】:

  • 遇到python错误时请包含回溯。粘贴它,然后使用编辑器工具栏上的{} 按钮像代码一样缩进。
  • 谢谢@MartijnPieters 我用回溯更新了我的问题。

标签: python python-3.x urllib


【解决方案1】:

在 python 3 中,urllib.request 对象是一个模块。您需要在此模块中调用 contained 对象。这是 Python 2 的一个重要变化,如果您使用的是示例代码,则需要考虑到这一点。

例如,创建Request 对象和开启器:

request = urllib.request.Request(url, headers=req_headers)
opener = urllib.request.build_opener()
response = opener.open(request)

仔细阅读documentation

【讨论】:

  • 谢谢,我的前两个项目是去年的python 2.x。我使用的是引用 urllib2 的示例代码的修改版本,我读过的现在已汇总到 urllib 中。现在我知道了这种差异,我会更加注意。
  • @Gimp:几个模块被合并和/或拆分成新的命名空间。 python 2 中的urllib2 分为urllib.errorurllib.request。您可能还想浏览What's new in Python 3.x 系列文档。
  • 在 Python 2 中,我必须使用来自 urlparse 模块的 parse() 方法。但是在 Python 3 中,您必须使用 from urllib import parse,然后使用 parse.urlparse()。这很棒。谢谢。
【解决方案2】:

urllib.request 是一个模块。 urllib.request.Request 是一个类。像您当前所做的那样调用模块会引发错误。您可能想要调用该类,如下所示:

request = urllib.request.Request(url, headers=req_headers)  # create a request object for the URL

您可能还想使用urllib.request 中的build_opener 而不仅仅是urllib

opener = urllib.request.build_opener()  # create an opener object

【讨论】:

  • 感谢您抽出宝贵时间回答我的问题 icktoofay。我给了你+1。 @Martijn 的编辑速度更快,帮助我首先解决了我的麻烦,同时提供了关于 python 2.x 和 3.x 之间差异的见解,但似乎你们都给出了相同的答案。再次感谢您的时间和精力。
【解决方案3】:

如果您通过使用@property 注释将返回方法声明为属性方法,也会发生这种情况。

【讨论】:

    猜你喜欢
    • 2017-06-17
    • 2014-09-21
    • 2022-01-09
    • 2021-12-26
    • 2011-05-30
    • 2021-11-22
    • 1970-01-01
    相关资源
    最近更新 更多