python – AttributeError: module object has no attribute urlopen

python – AttributeError: module object has no attribute urlopen

This works in Python 2.x.

For Python 3 look in the docs:

import urllib.request

with urllib.request.urlopen(http://www.python.org) as url:
    s = url.read()
    # Im guessing this would output the html source code ?
    print(s)

A Python 2+3 compatible solution is:

import sys

if sys.version_info[0] == 3:
    from urllib.request import urlopen
else:
    # Not Python 3 - today, it is most likely to be Python 2
    # But note that this might need an update when Python 4
    # might be around one day
    from urllib import urlopen


# Your code where you can use urlopen
with urlopen(http://www.python.org) as url:
    s = url.read()

print(s)

python – AttributeError: module object has no attribute urlopen

import urllib.request as ur
s = ur.urlopen(http://www.google.com)
sl = s.read()
print(sl)

In Python v3 the urllib.request is a module by itself, therefore urllib cannot be used here.

Leave a Reply

Your email address will not be published.