1

Am trying to test out urllib2. Here's my code:

import urllib2
response = urllib2.urlopen('http://pythonforbeginners.com/')
print response.info()
html = response.read()
response.close()

When I run it, I get:

Syntax Error: invalid syntax. Carrot points to line 3 (the print line). Any idea what's going on here? I'm just trying to follow a tutorial and this is the first thing they do...

Thanks, Mariogs

anon_swe
  • 8,791
  • 24
  • 85
  • 145
  • 2
    What version of Python are you using? – kichik Mar 22 '14 at 01:53
  • Just so you know, in most practical situations you will be better off using the `requests` library instead of the `urllib` module. That isn't related to the specific issues you're having here, though. – Andrew Gorcester Mar 22 '14 at 02:07

1 Answers1

3

In Python3 print is a function. Therefore it needs parentheses around its argument:

print(response.info())

In Python2, print is a statement, and hence does not require parentheses.


After correcting the SyntaxError, as alecxe points out, you'll probably encounter an ImportError next. That is because the Python2 module called urllib2 was renamed to urllib.request in Python3. So you'll need to change it to

import urllib.request as request
response = request.urlopen('http://pythonforbeginners.com/')

As you can see, the tutorial you are reading is meant for Python2. You might want to find a Python3 tutorial or Python3 urllib HOWTO to avoid running into more of these problems.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Then, why doesn't it throw an error on the `import` line? – alecxe Mar 22 '14 at 01:59
  • @alecxe: SyntaxErrors occur before ImportErrors. But you are right, that is probably the next problem to occur. – unutbu Mar 22 '14 at 02:00
  • @alecxe yeah so now I get that import error :) I tried adding parentheses but it says it ImportError: No module named 'urllib2'...ideas? – anon_swe Mar 22 '14 at 02:04
  • @unutbu I think `print` is still a statement in python2. (Unless you import the print function from the future). – Hyperboreus Mar 22 '14 at 02:04
  • @Mariogs there is no more `urllib2` in python 3: see http://stackoverflow.com/questions/6594620/python-3-2-unable-to-import-urllib2-importerror-no-module-named-urllib2 – alecxe Mar 22 '14 at 02:04
  • @Mariogs Because you are doing a python2 tutorial in python3... that's why. – Hyperboreus Mar 22 '14 at 02:05