]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
Find an icon's URL in the HTML.
[bookmarks_db.git] / Robots / parse_html.py
1 #! /usr/bin/env python
2 """
3    HTML Parser
4
5    Written by BroytMann. Copyright (C) 1997-2007 PhiloSoft Design
6 """
7
8
9 import sys
10 current_charset = sys.getdefaultencoding()
11 if current_charset == "ascii":
12    try:
13       import locale
14    except ImportError:
15       pass
16    else:
17       current_charset = locale.getpreferredencoding()
18 current_charset = current_charset.replace("windows-", "cp").lower()
19 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
20
21
22 from HTMLParser import HTMLParseError
23 from m_lib.net.www.html import HTMLParser as _HTMLParser
24
25
26 class HTMLHeadDone(Exception): pass
27
28
29 class HTMLParser(_HTMLParser):
30    def __init__(self, charset=None):
31       _HTMLParser.__init__(self)
32       self.charset = charset
33       self.meta_charset = 0
34       self.title = ''
35       self.refresh = ''
36
37    def end_head(self):
38       raise HTMLHeadDone()
39
40
41    def do_meta(self, attrs):
42       http_equiv = ""
43       content = ""
44
45       for attrname, value in attrs:
46          if value:
47             value = value.strip()
48             if attrname == 'http-equiv':
49                http_equiv = value.lower()
50             elif attrname == 'content':
51                content = value
52
53       if (not self.charset) and (http_equiv == "content-type"):
54          try:
55             # extract charset from "text/html; foo; charset=UTF-8; bar;"
56             self.charset = content.lower().split('charset=')[1].split(';')[0]
57             self.meta_charset = 1 # Remember that the charset was retrieved from
58                                   # META tag, not from the Content-Type header
59          except IndexError:
60             pass
61
62       if http_equiv == "refresh":
63          self.refresh = content
64
65
66    def start_title(self, attrs):
67       self.accumulator = ''
68
69    def end_title(self):
70       if not self.title: # use only the first title
71          self.title = self.accumulator
72
73
74    def do_link(self, attrs):
75       has_icon = False
76       href = None
77
78       for attrname, value in attrs:
79          if value:
80             value = value.strip().lower()
81             if (attrname == 'rel') and (value in ('icon', 'shortcut icon')):
82                has_icon = True
83             elif attrname == 'href':
84                href = value
85
86       if has_icon:
87          self.icon = href
88       else:
89          self.icon = None
90
91
92 import re
93 entity_re = re.compile("(&#[0-9]+;)")
94
95 def recode_entities(title, charset):
96    output = []
97    for part in entity_re.split(title):
98       if entity_re.match(part):
99          part = unichr(int(part[2:-1])).encode(charset, "replace")
100       output.append(part)
101
102    return ''.join(output)
103
104
105 def parse_html(filename, charset=None, log=None):
106    infile = open(filename, 'r')
107    parser = HTMLParser(charset)
108
109    for line in infile:
110       try:
111          parser.feed(line)
112       except (HTMLParseError, HTMLHeadDone):
113          break
114
115    infile.close()
116
117    try:
118       parser.close()
119    except (HTMLParseError, HTMLHeadDone):
120       pass
121
122    title = parser.title
123
124    if not parser.charset:
125       try:
126          unicode(title, "ascii")
127       except UnicodeDecodeError:
128          parser.charset = DEFAULT_CHARSET
129
130    if parser.charset:
131       parser.charset = parser.charset.replace("windows-", "cp").lower()
132
133    if parser.charset and (parser.charset <> current_charset):
134       try:
135          if parser.meta_charset:
136             if log: log("   META charset   : %s" % parser.charset)
137          else:
138             if log: log("   charset        : %s" % parser.charset)
139          if log: log("   title          : %s" % title)
140          title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
141          if log: log("   current charset: %s" % current_charset)
142          if log: log("   converted title: %s" % title)
143       except LookupError:
144          if log: log("   unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
145
146    parser.title = recode_entities(title, current_charset)
147    return parser
148
149
150 if __name__ == '__main__':
151    import sys
152    parser = parse_html(sys.argv[1])
153    print parser.charset
154    print parser.title
155    print parser.refresh
156    print parser.icon