0

I've been trying to do this with repl.it and have tried several solutions on this site, but none of them work. Right now, my code looks like

import urllib
url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345"
print (urllib.urlopen(url).read())

but it just says "AttributeError: module 'urllib' has no attribute 'urlopen'".

If I add import urllib.urlopen, it tells me there's no module named that. How can I fix my problem?

K. Michael
  • 75
  • 1
  • 9
  • See http://stackoverflow.com/a/25863131/4895040 – raymelfrancisco Nov 30 '16 at 03:45
  • Possible duplicate of of http://stackoverflow.com/questions/3969726/attributeerror-module-object-has-no-attribute-urlopen – Joe Nov 30 '16 at 03:48
  • Possible duplicate of [Python urllib urlopen not working](http://stackoverflow.com/questions/25863101/python-urllib-urlopen-not-working) – zondo Nov 30 '16 at 04:01

2 Answers2

4

The syntax you are using for the urllib library is from Python v2. The library has changed somewhat for Python v3. The new notation would look something more like:

import urllib.request
response = urllib.request.urlopen("http://www.google.com")
html = response.read()

The html object is just a string, with the returned HTML of the site. Much like the original urllib library, you should not expect images or other data files to be included in this returned object.

The confusing part here is that, in Python 3, this would fail if you did:

import urllib
response = urllib.request.urlopen("http://www.google.com")
html = response.read()

This strange module-importing behavior is, I am told, as intended and working. BUT it is non-intuitive and awkward. More importantly, for you, it makes the situation harder to debug. Enjoy.

john_science
  • 6,325
  • 6
  • 43
  • 60
  • Thanks, but for some reason it still isn't working in repl.it. It just says "urllib.error.URLError: " – K. Michael Nov 30 '16 at 04:23
  • @K.Michael That is the error you usually get if you are not connected to the internet. Sorry. Though, it could be a more subtle problem with the DNS servers. If you are running your code from a Raspberry Pi or connecting to the internet through a proxy, then DNS is more likely the issue. – john_science Nov 30 '16 at 14:41
2

Python3

import urllib
import requests
url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345"
r = urllib.request.urlopen(url).read()
print(r)

or

import urllib.request
url = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=12345"
r = urllib.request.urlopen(url).read()
print(r)
ie__ll
  • 21
  • 1