Importing urllib in Python problem

workspace
python

#1

Hi!

kind of a newbie question…
i’m trying to run this code in Python:

import urllib.request
import urllib.parse
import re

url = 'http://pythonprogramming.net
values = {‘s’:‘basics’,
‘submit’:‘search’}
data = urllib.parse.urlencode(values)
data = data.encode(‘utf-8’)
req = urllib.request.Request(url, data)
resp = urllib.request.urlopen(req)
respData = resp.read()

print(respData)

and i’m getting “ImportError: No module named request”

any idea why this is happening and how to fix it?

thanks!


#2

Replace the following lines:

import urllib.request
import urllib.parse

For just urllib:

import urllib

You can then use parse and request on your code.


#3

Hi!, thanks for the reply!

i did what you suggested and now i get this eror:
AttributeError: ‘module’ object has no attribute ‘parse’

and on each line containing the parse or request i have this red circle prompting:
Module ‘urllib’ has no ‘parse’ member (same with ‘request’)

how do i fix it?


#4

For encoding, just use urllib.urlencode, for request you might need to use urllib2.

I modified your code, give it a try according to your needs:

import urllib
import urllib2
import re

url = 'http://pythonprogramming.net'
values = {'s':'basics',
'submit':'search'}
data = urllib.urlencode(values)
data = data.encode('utf-8')
req = urllib2.Request(url, data)
resp = urllib2.urlopen(req)
respData = resp.read()

print(respData)

It is not tested, so let me know if you still get any errors.


#5

Worked like a charm!
so let me get these straight, any time i would like to use request i would need to use urllib2?


#6

Glad it worked.

As for your question, I do not think it urllib2 is necessary for a request but I think it is the recommended approach.

What is even more recommended is using Requests library. Although not a standard Python library, many consider it more robust, powerful, and easier to use than the standard HTTP Python libraries. I recommend you give it a try.


#7

#i found this problem it please solve me if possible .i found problem in urllib import

import urllib.request

import json
serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'
while True:
address = input('Enter Location: ')
if len(address)<1: break
url = serviceurl + urllib.parse.urlencode({‘sensor’:‘false’,‘address’:‘address’})
print(‘Retrived’,url)
uh = urllib.request.urlopen(url)
data = uh.read()
print(‘Retrived’,len(data),‘characters’)

try: js = json.loads(str(data))
except: js = None
if ‘status’ not in js or js[‘status’] != ‘Ok’:
print (’======Failure To Retrive=====’)
print(data)

print(json.dumps(js, indent=4))

lat = js[“results”][0][“geometry”][“location”][“lat”]
lng = js[“results”][0][“geometry”][“location”][“lng”]
print(‘lat’,lat,‘lng’,lng)


#8

Have you solved the problem?
I have also encountered this problem in python 3.6, and can’t import urllib2, only to import the urllib. If you solve it, please tell me