Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

python - urllib "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,))

I've been using this link for reference: http://docs.python.org/release/3.0.1/library/urllib.request.html

Traceback:

Traceback (most recent call last):
  File "C:ProjectLinkCrawlLinkCrawl.py", line 31, in <module>
    testURL = get_url('http://www.urlhere.filename.zip')
  File "C:ProjectLinkCrawlLinkCrawl.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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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)

Read the documentation carefully.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...