Rectangle 27 0

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


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

@Sergio: exactly! And through the indentation you see where your file is still opened.

Hello @eumiro, I have an error of "IndentationError: expected an indented block" when I type s = url.read(), may I ask how can I solve it please? x

Hi Eumiro, using the 'with' statement in Python I'm guessing it closes the connection automatically once it's done using it? Similar to a use statement in C#?

This works in Python 2.x.

Note
Rectangle 27 0

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


import urllib.request as ur

filehandler = ur.urlopen ('http://www.google.com')
for line in filehandler:
    print(line.strip())
Note
Rectangle 27 0

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.

Note
Rectangle 27 0

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


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)

A Python 2+3 compatible solution is:

Note