]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
Initialize parser.icon in case there are no <link> tags.
[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       self.icon = None
37
38    def end_head(self):
39       raise HTMLHeadDone()
40
41
42    def do_meta(self, attrs):
43       http_equiv = ""
44       content = ""
45
46       for attrname, value in attrs:
47          if value:
48             value = value.strip()
49             if attrname == 'http-equiv':
50                http_equiv = value.lower()
51             elif attrname == 'content':
52                content = value
53
54       if (not self.charset) and (http_equiv == "content-type"):
55          try:
56             # extract charset from "text/html; foo; charset=UTF-8; bar;"
57             self.charset = content.lower().split('charset=')[1].split(';')[0]
58             self.meta_charset = 1 # Remember that the charset was retrieved from
59                                   # META tag, not from the Content-Type header
60          except IndexError:
61             pass
62
63       if http_equiv == "refresh":
64          self.refresh = content
65
66
67    def start_title(self, attrs):
68       self.accumulator = ''
69
70    def end_title(self):
71       if not self.title: # use only the first title
72          self.title = self.accumulator
73
74
75    def do_link(self, attrs):
76       has_icon = False
77       href = None
78
79       for attrname, value in attrs:
80          if value:
81             value = value.strip().lower()
82             if (attrname == 'rel') and (value in ('icon', 'shortcut icon')):
83                has_icon = True
84             elif attrname == 'href':
85                href = value
86
87       if has_icon:
88          self.icon = href
89       else:
90          self.icon = None
91
92
93 import re
94 entity_re = re.compile("(&#[0-9]+;)")
95
96 def recode_entities(title, charset):
97    output = []
98    for part in entity_re.split(title):
99       if entity_re.match(part):
100          part = unichr(int(part[2:-1])).encode(charset, "replace")
101       output.append(part)
102
103    return ''.join(output)
104
105
106 def parse_html(filename, charset=None, log=None):
107    infile = open(filename, 'r')
108    parser = HTMLParser(charset)
109
110    for line in infile:
111       try:
112          parser.feed(line)
113       except (HTMLParseError, HTMLHeadDone):
114          break
115
116    infile.close()
117
118    try:
119       parser.close()
120    except (HTMLParseError, HTMLHeadDone):
121       pass
122
123    title = parser.title
124
125    if not parser.charset:
126       try:
127          unicode(title, "ascii")
128       except UnicodeDecodeError:
129          parser.charset = DEFAULT_CHARSET
130
131    if parser.charset:
132       parser.charset = parser.charset.replace("windows-", "cp").lower()
133
134    if parser.charset and (parser.charset <> current_charset):
135       try:
136          if parser.meta_charset:
137             if log: log("   META charset   : %s" % parser.charset)
138          else:
139             if log: log("   charset        : %s" % parser.charset)
140          if log: log("   title          : %s" % title)
141          title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
142          if log: log("   current charset: %s" % current_charset)
143          if log: log("   converted title: %s" % title)
144       except LookupError:
145          if log: log("   unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
146
147    parser.title = recode_entities(title, current_charset)
148    return parser
149
150
151 if __name__ == '__main__':
152    import sys
153    parser = parse_html(sys.argv[1])
154    print parser.charset
155    print parser.title
156    print parser.refresh
157    print parser.icon