rain
rain

Reputation: 21

python 3 import urllib.request module

I am learning to grab pictures from URL and found a Q&A here. Since it's Python 3, I changed import urllib to import urllib.request and

urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

to

urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg").

It doesn't work! It says AttributeError: 'module' object has no attribute 'urlretrieve'

I then changed urllib.urlretrieve to def request.urlretrieve and got SyntaxError: invalid syntax

I also tried def urlretrieve and it's not working either.

Could anyone tell me how to get it right? Thanks!

What if the URL contains more than one pic?

Upvotes: 1

Views: 5782

Answers (2)

nsane
nsane

Reputation: 1765

Since you have imported urllib.request module, doesn't it seem obvious that you should call its method urlretrieve(args) as urllib.request.urlretrieve(args).

  1. When you type import <module>, you call its method using <module>.method(args) (As specified in above code).

  2. Alternatively, you can import the module using from <module> import * and then call its method using method(args). Eg -

    from urllib.request import *

    urlretrieve(args).

  3. Another way is to only import the method you need to use in your program using from <module> import method and then call the method using method(args). Eg -

from urllib.request import urlretrieve and then call the method using

urlretrieve(args).

The urllib.request module for Python 3 is well documented here.

Upvotes: 0

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

You need to use:

from urllib import request
request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

You can use also use:

 import urllib.request
 urllib.request.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

Upvotes: 3

Related Questions