]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
Do not display too much titles if they are equal.
[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-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 parsers = []
15 try:
16    from parse_html_beautifulsoup import parse_html
17 except ImportError:
18    pass
19 else:
20    parsers.append(parse_html)
21
22 from parse_html_htmlparser import parse_html
23 parsers.append(parse_html)
24
25
26 import re
27 entity_re = re.compile("(&#[0-9]+;)")
28
29 def recode_entities(title, charset):
30    output = []
31    for part in entity_re.split(title):
32       if entity_re.match(part):
33          try:
34             part = unichr(int(part[2:-1])).encode(charset)
35          except UnicodeEncodeError:
36             pass # Leave the entity as is
37       output.append(part)
38
39    return ''.join(output)
40
41
42 def parse_html(filename, charset=None, log=None):
43    if charset:
44       try:
45          codecs.lookup(charset) # In case of unknown charset...
46       except (ValueError, LookupError):
47          charset = None         # ...try charset from HTML
48
49    for p in parsers:
50       parser = p(filename, charset)
51       if parser:
52          break
53       else:
54          if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
55
56    converted_title = title = parser.title
57    if not parser.charset:
58       try:
59          unicode(title, "ascii")
60       except UnicodeDecodeError:
61          parser.charset = DEFAULT_CHARSET
62
63    if parser.charset:
64       parser.charset = parser.charset.replace("windows-", "cp").lower()
65
66    if parser.charset and (parser.charset <> current_charset):
67       try:
68          if parser.meta_charset:
69             if log: log("   META charset   : %s" % parser.charset)
70          else:
71             if log: log("   HTTP charset   : %s" % parser.charset)
72          if log: log("   current charset: %s" % current_charset)
73          if log: log("   title          : %s" % title)
74          save_title = title
75          try:
76             converted_title = unicode(title, parser.charset).encode(current_charset)
77          except UnicodeError:
78             if parser.meta_charset and parser.charset.endswith("1252") and \
79                   not DEFAULT_CHARSET.endswith("1252") and (DEFAULT_CHARSET <> current_charset):
80                parser.charset = DEFAULT_CHARSET
81                if log: log("   incorrect conversion from cp1252, converting from %s" % DEFAULT_CHARSET)
82                converted_title = unicode(save_title, DEFAULT_CHARSET, "replace").encode(current_charset, "replace")
83             else:
84                converted_title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
85          if log and (converted_title <> title): log("   converted title: %s" % converted_title)
86       except LookupError:
87          if log: log("   unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
88    else:
89       if log: log("   title          : %s" % title)
90
91    final_title = recode_entities(converted_title, current_charset)
92    parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
93    final_title = ' '.join([s for s in parts if s])
94    if log and (final_title <> converted_title): log("   final title    : %s" % final_title)
95    parser.title = final_title
96    return parser
97
98
99 if __name__ == '__main__':
100    import sys
101    parser = parse_html(sys.argv[1], current_charset)
102    print parser.charset
103    print parser.title
104    print parser.refresh
105    print parser.icon