]> git.phdru.name Git - bookmarks_db.git/blob - parse_html/bkmk_parse_html.py
Fixed logging.
[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 # Statistics by parser - successfully parsed HTML pages:
24 # 4358 beautifulsoup
25 # 4310 htmlparser
26 # 4307 html5
27 # 4250 lxml
28
29 try:
30    from . import bkmk_ph_beautifulsoup
31 except ImportError:
32    pass
33 else:
34    bkmk_ph_beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
35    parsers.append(bkmk_ph_beautifulsoup.parse_html)
36
37 try:
38    from . import bkmk_ph_htmlparser
39 except ImportError:
40    pass
41 else:
42     parsers.append(bkmk_ph_htmlparser.parse_html)
43
44 try:
45    from . import bkmk_ph_html5
46 except ImportError:
47    pass
48 else:
49    parsers.append(bkmk_ph_html5.parse_html)
50
51 try:
52    from . import bkmk_ph_lxml
53 except ImportError:
54    pass
55 else:
56     parsers.append(bkmk_ph_lxml.parse_html)
57
58 # ElementTidy often segfaults
59 #try:
60 #   from . import bkmk_ph_etreetidy
61 #except ImportError:
62 #   pass
63 #else:
64 #   parsers.append(bkmk_ph_etreetidy.parse_html)
65
66 import re
67 from htmlentitydefs import name2codepoint
68
69 entity_re = re.compile("(&\w+;)")
70 num_entity_re = re.compile("(&#[0-9]+;)")
71
72 def recode_entities(title, charset):
73    output = []
74    for part in entity_re.split(title):
75       if part not in ("&amp;", "&lt;", "&gt;", "&quot;") and \
76             entity_re.match(part):
77          _part = name2codepoint.get(part[1:-1], None)
78          if _part is not None:
79              part = unichr(_part).encode(charset)
80       output.append(part)
81    title = ''.join(output)
82
83    output = []
84    for part in num_entity_re.split(title):
85       if num_entity_re.match(part):
86          try:
87             part = unichr(int(part[2:-1])).encode(charset)
88          except UnicodeEncodeError:
89             pass # Leave the entity as is
90       output.append(part)
91
92    return ''.join(output)
93
94
95 def parse_html(filename, charset=None, log=None):
96    if not parsers:
97        return None
98
99    if charset:
100       try:
101          codecs.lookup(charset) # In case of unknown charset...
102       except (ValueError, LookupError):
103          charset = None         # ...try charset from HTML
104
105    charsets = [universal_charset, DEFAULT_CHARSET]
106    if charset:
107       charset = charset.lower().replace("windows-", "cp")
108       if charset in charsets:
109          charsets.remove(charset)
110       charsets.insert(0, charset)
111
112    #_parsers = []
113    for p in parsers:
114       parser = None
115       for c in charsets:
116          try:
117             parser = p(filename, c, log)
118          except UnicodeError:
119             pass
120          else:
121             if parser:
122                #if log: log("   Parser %s: ok" % p.__module__)
123                #_parsers.append(parser)
124                break
125       else:
126          if log: log("   Parser %s: fail" % p.__module__)
127       if parser:
128          break
129
130    #if not _parsers:
131    if not parser:
132        if log: log("   All parser has failed")
133        return None
134
135    #parser = _parsers[0]
136    if log: log("   Using %s" % p.__module__)
137
138    converted_title = title = parser.title
139    if title and (not parser.charset):
140       try:
141          unicode(title, "ascii")
142       except UnicodeDecodeError:
143          parser.charset = DEFAULT_CHARSET
144
145    if parser.charset:
146       parser.charset = parser.charset.lower().replace("windows-", "cp")
147
148    if title and parser.charset and (
149          (parser.charset <> universal_charset) or
150          ((not charset) or (charset <> parser.charset))):
151       try:
152          if parser.meta_charset:
153             if log: log("   META charset   : %s" % parser.charset)
154          elif (not charset) or (charset <> parser.charset):
155             if log: log("   guessed charset: %s" % parser.charset)
156          #if log: log("   current charset: %s" % universal_charset)
157          if log: log("   title          : %s" % title)
158          if parser.charset <> universal_charset:
159             try:
160                converted_title = unicode(title, parser.charset).encode(universal_charset)
161             except UnicodeError:
162                if log: log("   incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
163                converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
164                parser.charset = DEFAULT_CHARSET
165          if log and (converted_title <> title): log("   converted title: %s" % converted_title)
166       except LookupError:
167          if log: log("   unknown charset: '%s'" % parser.charset)
168    else:
169       if log: log("   title          : %s" % title)
170
171    if title:
172       final_title = recode_entities(converted_title, universal_charset)
173       parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
174       final_title = ' '.join([s for s in parts if s])
175       if log and (final_title <> converted_title): log("   final title    : %s" % final_title)
176       parser.title = final_title
177
178    icon = parser.icon
179    if isinstance(icon, unicode):
180        try:
181            parser.icon = icon.encode('ascii')
182        except UnicodeEncodeError:
183            if parser.charset:
184                parser.icon = icon.encode(parser.charset)
185    return parser