Python3: Urllib.request isn't working

I put this into my code:

import urllib

print(urllib.request("http://www.google.com"))
input()

I get an error saying:

Traceback (most recent call last):
  File "C:\Users\David\Desktop\Interwebz.py", line 3, in <module>
    print(urllib.request("http://www.google.com"))
AttributeError: module 'urllib' has no attribute 'request'

I have no idea what's wrong. I checked

C:/Users/David/AppData/Local/Programs/Python/Python35-32/Lib/urllib

but I see nothing wrong with the files.

Request seems to not exist in urllib. (even though I found a request.py file in the urllib folder)

Upvotes: 0

Views: 570

Answers (2)

Mayank Jain
Mayank Jain

Reputation: 476

There were a long explanation of this in their document, but let me make it short, its init.py is empty. so have to import particular module of it. you were importing the library urllib and using its 'request' method, but for the case of urllib the import is like below.

import urllib.request

then it will work

all the method of urllib have to be imported like this and used.

other examples

import urllib.parse, urllib.error

Upvotes: 0

Simon Black
Simon Black

Reputation: 923

You don't actually say what you want to do but I assume you want to open a URL and read the response.

import urllib.request

with urllib.request.urlopen("http://www.google.com") as f:
    print(f.read())

Upvotes: 1

Related Questions