6

これは私の 3 番目の 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
4

3 に答える 3

19

Python 3 では、urllib.requestオブジェクトはモジュールです。このモジュールに含まれるオブジェクトを呼び出す必要があります。これは Python 2 からの重要な変更です。サンプル コードを使用している場合は、それを考慮する必要があります。

たとえば、Requestオブジェクトとオープナーを作成します。

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

ドキュメントをよく読んでください。

于 2012-10-07T19:41:10.400 に答える
5

urllib.requestモジュールです。urllib.request.Requestクラスです。現在行っているようにモジュールを呼び出すと、エラーが発生します。おそらく、次のようにクラスを呼び出したいと思うでしょう:

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

また、単に ではなくbuild_openerofを使用することもできます。urllib.requesturllib

opener = urllib.request.build_opener()  # create an opener object
于 2012-10-07T19:41:24.517 に答える