views:

42

answers:

3

First time working with the HTMLParser module. Trying to use standard string formatting on the ouput, but it's giving me an error. The following code:

import urllib2
from HTMLParser import HTMLParser

class LinksParser(HTMLParser):
    def __init__(self, url):
        HTMLParser.__init__(self)
        req = urllib2.urlopen(url)
        self.feed(req.read())

    def handle_starttag(self, tag, attrs):
        if tag != 'a': return
        for name, value in attrs:
        print("Found Link --> {]".format(value))


if __name__ == "__main__":
    LinksParser("http://www.facebook.com"

Produces the following error:

File "C:\Users\workspace\test\src\test.py", line 15, in handle_starttag  
print("Found Link --> {]".format(value))  
ValueError: unmatched '{' in format
A: 

This format string looks broken: print("Found Link --> {]".format(value)). You need to change this to print("Found Link --> {key}".format(key = value)).

Manoj Govindan
A: 

There are several problems

  • the print statement in handle_starttag should be indented
  • in the last line you're missing the closing parenthesis
  • in the print statement in handle_starttag you should use {0} instead of {]
Andre Holzner
+1  A: 
print("Found Link --> {]".format(value)) 

Should instead be:

print("Found Link --> {}".format(value))

You used a square bracket instead of a brace.

Coding District
Wow, I feel silly. Good eye catching that. Lol, perhaps I should increase the font size of my editor. :) Working fine now.
Stev0