ImportError: No module named 'urllib2' Python 3

ImportError: No module named 'urllib2' Python 3

下面的代码在 Python 2 上工作正常,但在 Python 3 上我收到错误:

"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()

请告诉我错误的原因。

谢谢。

urllib 和 urllib2 模块在 python3 中合并为 urllib。如果你想让你的代码与 2.x 和 3.x 兼容,我建议你查看 six module

检查Whosebug 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'))