Created
September 8, 2008 10:49
-
-
Save mytrile/9413 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import htmllib | |
import formatter | |
import string | |
import urllib, urlparse | |
class myParser(htmllib.HTMLParser): | |
def __init__(self, base): | |
htmllib.HTMLParser.__init__(self, formatter.NullFormatter()) | |
self.anchors = [] | |
self.base = base | |
def anchor_bgn(self, href, name, type): | |
self.save_bgn() | |
if self.base: | |
self.anchor = urlparse.urljoin(self.base, href) | |
else: | |
self.anchor = href | |
def anchor_end(self): | |
text = string.strip(self.save_end()) | |
if self.anchor and text: | |
self.anchors.append((self.anchor, text)) | |
if __name__ == '__main__': | |
URL = "http://www.google.com" | |
f = urllib.urlopen(URL) | |
p = myParser(URL) | |
p.feed(f.read()) | |
p.close() | |
print "anchors =", p.anchors | |
print "title =", p.title |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment