]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
680ad5573a741bb99402449a77d969202e49abde
[bookmarks_db.git] / Robots / parse_html.py
1 #! /usr/bin/env python
2 """
3    HTML Parsers wrapper
4
5    Written by BroytMann. Copyright (C) 1997-2008 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 try:
15    import parse_html_beautifulsoup
16    parse_html_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
17 except ImportError:
18    pass
19 else:
20    parsers.append(parse_html_beautifulsoup.parse_html)
21
22 from parse_html_htmlparser import parse_html
23 parsers.append(parse_html)
24
25
26 import re
27 from htmlentitydefs import name2codepoint
28
29 entity_re = re.compile("(&\w+;)")
30 num_entity_re = re.compile("(&#[0-9]+;)")
31
32 def recode_entities(title, charset):
33    output = []
34    for part in entity_re.split(title):
35       if part not in ("&", "<", ">", "&quote;", " ") and \
36             entity_re.match(part):
37          part = unichr(name2codepoint.get(part[1:-1], part)).encode(charset)
38       output.append(part)
39    title = ''.join(output)
40
41    output = []
42    for part in num_entity_re.split(title):
43       if num_entity_re.match(part):
44          try:
45             part = unichr(int(part[2:-1])).encode(charset)
46          except UnicodeEncodeError:
47             pass # Leave the entity as is
48       output.append(part)
49
50    return ''.join(output)
51
52
53 def parse_html(filename, charset=None, log=None):
54    if charset:
55       try:
56          codecs.lookup(charset) # In case of unknown charset...
57       except (ValueError, LookupError):
58          charset = None         # ...try charset from HTML
59
60    for p in parsers:
61       charsets = [universal_charset, DEFAULT_CHARSET]
62       if charset not in charsets:
63          charsets.insert(0, charset)
64       parser = None
65       for c in charsets:
66          try:
67             parser = p(filename, c)
68             break
69          except UnicodeEncodeError:
70             pass
71       if parser:
72          break
73       else:
74          if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
75
76    converted_title = title = parser.title
77    if not parser.charset:
78       try:
79          unicode(title, "ascii")
80       except UnicodeDecodeError:
81          parser.charset = DEFAULT_CHARSET
82
83    if parser.charset:
84       parser.charset = parser.charset.replace("windows-", "cp").lower()
85
86    if parser.charset and (parser.charset <> universal_charset):
87       try:
88          if parser.meta_charset:
89             if log: log("   META charset   : %s" % parser.charset)
90          else:
91             if log: log("   guessed charset: %s" % parser.charset)
92          if log: log("   current charset: %s" % universal_charset)
93          if log: log("   title          : %s" % title)
94          try:
95             converted_title = unicode(title, parser.charset).encode(universal_charset)
96          except UnicodeError:
97             if log: log("   incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
98             converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
99             parser.charset = DEFAULT_CHARSET
100          if log and (converted_title <> title): log("   converted title: %s" % converted_title)
101       except LookupError:
102          if log: log("   unknown charset: `%s' or `%s'" % (parser.charset, universal_charset))
103    else:
104       if log: log("   title          : %s" % title)
105
106    final_title = recode_entities(converted_title, universal_charset)
107    parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
108    final_title = ' '.join([s for s in parts if s])
109    if log and (final_title <> converted_title): log("   final title    : %s" % final_title)
110    parser.title = final_title
111    return parser
112
113
114 if __name__ == '__main__':
115    import sys
116    from m_lib.defenc import default_encoding
117    current_charset = default_encoding.replace("windows-", "cp")
118
119    parser = parse_html(sys.argv[1], universal_charset,
120       log=lambda s: sys.stdout.write(s + '\n'))
121    print "   refresh:", parser.refresh
122    print "   icon   :", parser.icon