]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
Do not parse meta charset if there is HTTP charset.
[bookmarks_db.git] / Robots / parse_html.py
1 #! /usr/bin/env python
2 """
3    HTML Parsers wrapper
4
5    Written by Broytman. Copyright (C) 1997-2010 PhiloSoft Design
6 """
7
8 import codecs
9
10 universal_charset = "utf-8"
11 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
12
13 parsers = []
14
15 try:
16    import parse_html_html5
17 except ImportError:
18    pass
19 else:
20    parsers.append(parse_html_html5.parse_html)
21
22 try:
23    import parse_html_beautifulsoup
24    parse_html_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
25 except ImportError:
26    pass
27 else:
28    parsers.append(parse_html_beautifulsoup.parse_html)
29
30 from parse_html_htmlparser import parse_html
31 parsers.append(parse_html)
32
33
34 import re
35 from htmlentitydefs import name2codepoint
36
37 entity_re = re.compile("(&\w+;)")
38 num_entity_re = re.compile("(&#[0-9]+;)")
39
40 def recode_entities(title, charset):
41    output = []
42    for part in entity_re.split(title):
43       if part not in ("&", "<", ">", """) and \
44             entity_re.match(part):
45          _part = name2codepoint.get(part[1:-1], None)
46          if _part is not None:
47              part = unichr(_part).encode(charset)
48       output.append(part)
49    title = ''.join(output)
50
51    output = []
52    for part in num_entity_re.split(title):
53       if num_entity_re.match(part):
54          try:
55             part = unichr(int(part[2:-1])).encode(charset)
56          except UnicodeEncodeError:
57             pass # Leave the entity as is
58       output.append(part)
59
60    return ''.join(output)
61
62
63 def parse_html(filename, charset=None, log=None):
64    if charset:
65       try:
66          codecs.lookup(charset) # In case of unknown charset...
67       except (ValueError, LookupError):
68          charset = None         # ...try charset from HTML
69
70    charsets = [universal_charset, DEFAULT_CHARSET]
71    if charset:
72       charset = charset.lower().replace("windows-", "cp")
73       if charset in charsets:
74          charsets.remove(charset)
75       charsets.insert(0, charset)
76
77    for p in parsers:
78       parser = None
79       for c in charsets:
80          try:
81             parser = p(filename, c, log)
82             break
83          except UnicodeEncodeError:
84             pass
85       if parser:
86          break
87       else:
88          if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
89
90    converted_title = title = parser.title
91    if title and (not parser.charset):
92       try:
93          unicode(title, "ascii")
94       except UnicodeDecodeError:
95          parser.charset = DEFAULT_CHARSET
96
97    if parser.charset:
98       parser.charset = parser.charset.lower().replace("windows-", "cp")
99
100    if title and parser.charset and (
101          (parser.charset <> universal_charset) or
102          ((not charset) or (charset <> parser.charset))):
103       try:
104          if parser.meta_charset:
105             if log: log("   META charset   : %s" % parser.charset)
106          elif (not charset) or (charset <> parser.charset):
107             if log: log("   guessed charset: %s" % parser.charset)
108          if log: log("   current charset: %s" % universal_charset)
109          if log: log("   title          : %s" % title)
110          if parser.charset <> universal_charset:
111             try:
112                converted_title = unicode(title, parser.charset).encode(universal_charset)
113             except UnicodeError:
114                if log: log("   incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
115                converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
116                parser.charset = DEFAULT_CHARSET
117          if log and (converted_title <> title): log("   converted title: %s" % converted_title)
118       except LookupError:
119          if log: log("   unknown charset: '%s'" % parser.charset)
120    else:
121       if log: log("   title          : %s" % title)
122
123    if title:
124       final_title = recode_entities(converted_title, universal_charset)
125       parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
126       final_title = ' '.join([s for s in parts if s])
127       if log and (final_title <> converted_title): log("   final title    : %s" % final_title)
128       parser.title = final_title
129    return parser
130
131
132 if __name__ == '__main__':
133    import sys
134
135    l = len(sys.argv)
136    if l == 3:
137       filename = sys.argv[1]
138       charset = sys.argv[2]
139    elif l == 2:
140       filename = sys.argv[1]
141       charset = universal_charset
142    else:
143       sys.exit("Usage: %s filename [charset]" % sys.argv[0])
144
145    parser = parse_html(filename, charset, log=lambda s: sys.stdout.write(s + '\n'))
146    print "   refresh:", parser.refresh
147    print "   icon   :", parser.icon