]> git.phdru.name Git - bookmarks_db.git/blob - parse_html/bkmk_parse_html.py
Changed the order or parser according to their success rate.
[bookmarks_db.git] / parse_html / bkmk_parse_html.py
1 """HTML Parsers
2
3 This file is a part of Bookmarks database and Internet robot.
4 """
5
6 __version__ = "$Revision$"[11:-2]
7 __revision__ = "$Id$"[5:-2]
8 __date__ = "$Date$"[7:-2]
9 __author__ = "Oleg Broytman <phd@phdru.name>"
10 __copyright__ = "Copyright (C) 1997-2011 PhiloSoft Design"
11 __license__ = "GNU GPL"
12
13 __all__ = ['parse_html', 'universal_charset']
14
15
16 import codecs
17
18 universal_charset = "utf-8"
19 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
20
21 parsers = []
22
23 try:
24    from . import bkmk_ph_beautifulsoup
25 except ImportError:
26    pass
27 else:
28    bkmk_ph_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
29    parsers.append(bkmk_ph_beautifulsoup.parse_html)
30
31 try:
32    from . import bkmk_ph_html5
33 except ImportError:
34    pass
35 else:
36    parsers.append(bkmk_ph_html5.parse_html)
37
38 try:
39    from . import bkmk_ph_lxml
40 except ImportError:
41    pass
42 else:
43     parsers.append(bkmk_ph_lxml.parse_html)
44
45 try:
46    from . import bkmk_ph_htmlparser
47 except ImportError:
48    pass
49 else:
50     parsers.append(bkmk_ph_htmlparser.parse_html)
51
52 # ElementTidy often segfaults
53 #try:
54 #   from . import bkmk_ph_etreetidy
55 #except ImportError:
56 #   pass
57 #else:
58 #   parsers.append(bkmk_ph_etreetidy.parse_html)
59
60 import re
61 from htmlentitydefs import name2codepoint
62
63 entity_re = re.compile("(&\w+;)")
64 num_entity_re = re.compile("(&#[0-9]+;)")
65
66 def recode_entities(title, charset):
67    output = []
68    for part in entity_re.split(title):
69       if part not in ("&amp;", "&lt;", "&gt;", "&quot;") and \
70             entity_re.match(part):
71          _part = name2codepoint.get(part[1:-1], None)
72          if _part is not None:
73              part = unichr(_part).encode(charset)
74       output.append(part)
75    title = ''.join(output)
76
77    output = []
78    for part in num_entity_re.split(title):
79       if num_entity_re.match(part):
80          try:
81             part = unichr(int(part[2:-1])).encode(charset)
82          except UnicodeEncodeError:
83             pass # Leave the entity as is
84       output.append(part)
85
86    return ''.join(output)
87
88
89 import os
90 BKMK_DEBUG_HTML_PARSERS = os.environ.get("BKMK_DEBUG_HTML_PARSERS")
91
92 def parse_html(filename, charset=None, log=None):
93    if not parsers:
94        return None
95
96    if charset:
97       try:
98          codecs.lookup(charset) # In case of unknown charset...
99       except (ValueError, LookupError):
100          charset = None         # ...try charset from HTML
101
102    charsets = [universal_charset, DEFAULT_CHARSET]
103    if charset:
104       charset = charset.lower().replace("windows-", "cp")
105       if charset in charsets:
106          charsets.remove(charset)
107       charsets.insert(0, charset)
108
109    if BKMK_DEBUG_HTML_PARSERS:
110       _parsers = []
111    for p in parsers:
112       parser = None
113       for c in charsets:
114          try:
115             parser = p(filename, c, log)
116          except UnicodeError:
117             pass
118          else:
119             if parser:
120                if BKMK_DEBUG_HTML_PARSERS:
121                   if log: log("   Parser %s: ok" % p.__module__)
122                   _parsers.append((p, parser))
123                break
124       else:
125          if log: log("   Parser %s: fail" % p.__module__)
126       if not BKMK_DEBUG_HTML_PARSERS and parser:
127          break
128
129    if BKMK_DEBUG_HTML_PARSERS:
130       if not _parsers:
131          if log: log("   All parsers have failed")
132          return None
133    elif not parser:
134        if log: log("   All parsers have failed")
135        return None
136
137    if BKMK_DEBUG_HTML_PARSERS:
138       p, parser = _parsers[0]
139    if log: log("   Using %s" % p.__module__)
140
141    converted_title = title = parser.title
142    if title and (not parser.charset):
143       try:
144          unicode(title, "ascii")
145       except UnicodeDecodeError:
146          parser.charset = DEFAULT_CHARSET
147
148    if parser.charset:
149       parser.charset = parser.charset.lower().replace("windows-", "cp")
150
151    if title and parser.charset and (
152          (parser.charset <> universal_charset) or
153          ((not charset) or (charset <> parser.charset))):
154       try:
155          if parser.meta_charset:
156             if log: log("   META charset   : %s" % parser.charset)
157          elif (not charset) or (charset <> parser.charset):
158             if log: log("   guessed charset: %s" % parser.charset)
159          #if log: log("   current charset: %s" % universal_charset)
160          if log: log("   title          : %s" % title)
161          if parser.charset <> universal_charset:
162             try:
163                converted_title = unicode(title, parser.charset).encode(universal_charset)
164             except UnicodeError:
165                if log: log("   incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
166                converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
167                parser.charset = DEFAULT_CHARSET
168          if log and (converted_title <> title): log("   converted title: %s" % converted_title)
169       except LookupError:
170          if log: log("   unknown charset: '%s'" % parser.charset)
171    else:
172       if log: log("   title          : %s" % title)
173
174    if title:
175       final_title = recode_entities(converted_title, universal_charset)
176       parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
177       final_title = ' '.join([s for s in parts if s])
178       if log and (final_title <> converted_title): log("   final title    : %s" % final_title)
179       parser.title = final_title
180
181    icon = parser.icon
182    if isinstance(icon, unicode):
183        try:
184            parser.icon = icon.encode('ascii')
185        except UnicodeEncodeError:
186            if parser.charset:
187                parser.icon = icon.encode(parser.charset)
188    return parser