urllib"模块对象不可调用"

dan*_*rak 5 python urllib python-3.x

这是我的第三个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,))
Run Code Online (Sandbox Code Playgroud)

我一直在使用此链接作为参考: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
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 15

在python 3中,urllib.request对象是一个模块.您需要调用此模块中包含的对象.这是Python 2的一个重要更改,如果您使用示例代码,则需要将其考虑在内.

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

request = urllib.request.Request(url, headers=req_headers)
opener = urllib.request.build_opener()
response = opener.open(request)
Run Code Online (Sandbox Code Playgroud)

仔细阅读文档.


ick*_*fay 5

urllib.request是一个模块.urllib.request.Request是一个班级.调用像您当前正在执行的模块会引发错误.您可能想要调用该类,如下所示:

request = urllib.request.Request(url, headers=req_headers)  # create a request object for the URL
Run Code Online (Sandbox Code Playgroud)

你也可能想使用build_openerurllib.request,而不仅仅是urllib:

opener = urllib.request.build_opener()  # create an opener object
Run Code Online (Sandbox Code Playgroud)