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.
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.
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.
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.
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.
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'))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With