26
votes

I would like to import urllib to use the function 'request'. However, I encountered an error when trying to do so. I tried pip install urllib but still had the same error. I am using Python 3.6. Really appreciate any help.

i do import urllib.request using this code:

import urllib.request, urllib.parse, urllib.error 
fhand = urllib.request.urlopen('data.pr4e.org/romeo.txt') 
counts = dict()
for line in fhand: 
    words = line.decode().split() 
for word in words: 
    counts[word] = counts.get(word, 0) + 1 
print(counts) 

but it gives me this error: ModuleNotFoundError: No Module named 'urllib.parse'; 'urllib' is not a package

here is a screenshot for the error

5
What OS, what were the errors etc?kabanus
i'm using windows. i edited the question with more details and a screenshot of the problem. please check it.Mohamed Mahdi
Did you try from urllib import request?Jakob Lovern
How did you install Python3? Please try to give all the information so people can answer your question.kabanus
always put full error message (Traceback) in question (as text, not screenshot). There are other useful informations.furas

5 Answers

44
votes

urllib is a standard library, you do not have to install it. Simply import urllib

5
votes

The corrected code is

import urllib.request
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
counts = dict()
for line in fhand: 
    words = line.decode().split() 
for word in words: 
    counts[word] = counts.get(word, 0) + 1 
print(counts) 

running the code above produces

{'Who': 1, 'is': 1, 'already': 1, 'sick': 1, 'and': 1, 'pale': 1, 'with': 1, 'grief': 1}
4
votes

urllib is a standard python library (built-in) so you don't have to install it. just import it if you need to use request by:

import urllib.request

if it's not work maybe you compiled python in wrong way, so be kind and give us more details.

2
votes

This happens because your local module named urllib.py shadows the installed requests module you are trying to use. The current directory is preapended to sys.path, so the local name takes precedence over the installed name.

An extra debugging tip when this comes up is to look at the Traceback carefully, and realize that the name of your script in question is matching the module you are trying to import.

Rename your file to something else like url.py. Then It is working fine. Hope it helps!

0
votes

yu have to install the correct version for your computer 32 or 63 bits thats all