]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
/usr/bin/env python
[bookmarks_db.git] / Robots / parse_html.py
1 #! /usr/bin/env python
2 """
3    HTML Parser
4
5    Written by BroytMann. Copyright (C) 1997-2005 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 import re
75 entity_re = re.compile("(&#[0-9]+;)")
76
77 def recode_entities(title, charset):
78    output = []
79    for part in entity_re.split(title):
80       if entity_re.match(part):
81          part = unichr(int(part[2:-1])).encode(charset, "replace")
82       output.append(part)
83
84    return ''.join(output)
85
86
87 def parse_html(filename, charset=None, log=None):
88    infile = open(filename, 'r')
89    parser = HTMLParser(charset)
90
91    for line in infile:
92       try:
93          parser.feed(line)
94       except (HTMLParseError, HTMLHeadDone):
95          break
96
97    infile.close()
98
99    try:
100       parser.close()
101    except (HTMLParseError, HTMLHeadDone):
102       pass
103
104    title = parser.title
105
106    if not parser.charset:
107       try:
108          unicode(title, "ascii")
109       except UnicodeDecodeError:
110          parser.charset = DEFAULT_CHARSET
111
112    if parser.charset:
113       parser.charset = parser.charset.replace("windows-", "cp").lower()
114
115    if parser.charset and (parser.charset <> current_charset):
116       try:
117          if parser.meta_charset:
118             if log: log("   META charset   : %s" % parser.charset)
119          else:
120             if log: log("   charset        : %s" % parser.charset)
121          if log: log("   title          : %s" % title)
122          title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
123          if log: log("   current charset: %s" % current_charset)
124          if log: log("   converted title: %s" % title)
125       except LookupError:
126          if log: log("   unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
127
128    parser.title = recode_entities(title, current_charset)
129    return parser
130
131
132 if __name__ == '__main__':
133    import sys
134    parser = parse_html(sys.argv[1])
135    print parser.charset
136    print parser.title
137    print parser.refresh