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

2
  • 2
    What version of Python are you using? Commented Mar 22, 2014 at 1: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. Commented Mar 22, 2014 at 2:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Then, why doesn't it throw an error on the import line?
@alecxe: SyntaxErrors occur before ImportErrors. But you are right, that is probably the next problem to occur.
@alecxe yeah so now I get that import error :) I tried adding parentheses but it says it ImportError: No module named 'urllib2'...ideas?
@unutbu I think print is still a statement in python2. (Unless you import the print function from the future).
@Mariogs there is no more urllib2 in python 3: see stackoverflow.com/questions/6594620/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.