Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ImportError: No module named 'urllib2' Python 3 [duplicate]

Tags:

The below code is working fine on Python 2 but on Python 3 I get the error:

"ImportError: No module named 'urllib2'"

import urllib2    
peticion = 'I'm XML'
url_test = 'I'm URL'
req = urllib2.Request(url=url_test,
                      data=peticion,
                      headers={'Content-Type': 'application/xml'})
respuesta = urllib2.urlopen(req)
print(respuesta)
print(respuesta.read())
respuesta.open()

Please suggest me the reason of error.

Thank you.

like image 573
Jordi Salom Avatar asked Jan 12 '16 09:01

Jordi Salom


People also ask

How do I fix No module named urllib2?

The Python "ModuleNotFoundError: No module named 'urllib2'" occurs because the urllib2 module has been split into urllib. request and urllib. response in Python 3. To solve the error, import the module as from urllib.

How do I import urllib2 in Python 3?

Simple urllib2 scriptimport urllib2 response = urllib2. urlopen('http://python.org/') print "Response:", response # Get the URL. This gets the real URL. print "The URL is: ", response.

Is Urllib built in Python 3?

The urllib module in Python 3 allows you access websites via your program. This opens up as many doors for your programs as the internet opens up for you. urllib in Python 3 is slightly different than urllib2 in Python 2, but they are mostly the same.

What is the difference between Urllib and urllib2?

urllib2 can accept a Request object to set the headers for a URL request, urllib accepts only a URL. That means, you cannot masquerade your User Agent string etc. urllib provides the urlencode method which is used for the generation of GET query strings, urllib2 doesn't have such a function.


2 Answers

check StackOverflow Link

import urllib.request
url = "http://www.google.com/"
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
print (response.read().decode('utf-8'))
like image 165
Prashant Puri Avatar answered Sep 27 '22 22:09

Prashant Puri


The urllib and urllib2 modules are merged together in python3 as urllib. If you want to make your code compatible with both 2.x and 3.x, I would advise you to look into the six module

like image 34
Alexander Ejbekov Avatar answered Sep 27 '22 21:09

Alexander Ejbekov