Search code examples
pythonmoduleurlliburllib2

python error while using urllib module


I was making python http banner grabber using urllib but it gives me an error.

I was not able it import urllib2 (module not found error) so tried with with urllib instead.

Here's the code , what's wrong with it?

#!/usr/bin/env python
import urllib   
url=urllib.urlopen('www.bing.com')
print (url.info())

Error:

AttributeError: 'module' object has no attribute 'urlopen'

Solution

  • You are using Python 3; use urllib.request instead.

    import urllib.request
    
    url = urllib.request.urlopen('http://www.bing.com')
    print(url.info())
    

    This is documented at the top of the urllib2 page:

    Note: The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.