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