模块对象不可调用

模块对象不可调用

本文介绍了urllib“模块对象不可调用"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

This is my third python project, and I've received an error message: 'module object' is not callable.

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

I know that this means I'm referencing a variable or function incorrectly. But trial and error hasn't been able to help me solve this.

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

I've been using this link for reference: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 3 中,urllib.request 对象是一个模块.你需要在这个模块中调用包含的对象.这是与 Python 2 相比的重要更改,如果您使用示例代码,则需要考虑到这一点.

In python 3, the urllib.request object is a module. You need to call objects contained in this module. This is an important change from Python 2, if you are using example code you need to take that into account.

例如,创建Request对象和opener:

For example, creating the Request object and the opener:

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

仔细阅读文档.

这篇关于urllib“模块对象不可调用"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:32