20

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.

Anton Protopopov
  • 30,354
  • 12
  • 88
  • 93
Jordi Salom
  • 361
  • 2
  • 5
  • 14

2 Answers2

36

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'))
Community
  • 1
  • 1
Prashant Puri
  • 2,324
  • 1
  • 15
  • 21
3

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

Alexander Ejbekov
  • 5,594
  • 1
  • 26
  • 26