]> git.phdru.name Git - bookmarks_db.git/blob - parse_html/__init__.py
Report what parser is in use.
[bookmarks_db.git] / parse_html / __init__.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']
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 beautifulsoup
25 except ImportError:
26    pass
27 else:
28    beautifulsoup.DEFAULT_CHARSET = DEFAULT_CHARSET
29    parsers.append(beautifulsoup.parse_html)
30
31 try:
32    from .lxml import parse_html
33 except ImportError:
34    pass
35 else:
36     parsers.append(parse_html)
37
38 try:
39    from .htmlparser import parse_html
40 except ImportError:
41    pass
42 else:
43     parsers.append(parse_html)
44
45 try:
46    from . import html5
47 except ImportError:
48    pass
49 else:
50    parsers.append(html5.parse_html)
51
52 # ElementTidy often segfaults
53 #try:
54 #   from . import etreetidy
55 #except ImportError:
56 #   pass
57 #else:
58 #   parsers.append(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 def parse_html(filename, charset=None, log=None):
90    if not parsers:
91        return None
92
93    if charset:
94       try:
95          codecs.lookup(charset) # In case of unknown charset...
96       except (ValueError, LookupError):
97          charset = None         # ...try charset from HTML
98
99    charsets = [universal_charset, DEFAULT_CHARSET]
100    if charset:
101       charset = charset.lower().replace("windows-", "cp")
102       if charset in charsets:
103          charsets.remove(charset)
104       charsets.insert(0, charset)
105
106    for p in parsers:
107       parser = None
108       for c in charsets:
109          try:
110             parser = p(filename, c, log)
111          except UnicodeEncodeError:
112             pass
113          else:
114             break
115       if parser:
116          break
117       else:
118          if log: log("Parser %s.%s failed, trying next one." % (p.__module__, p.__name__))
119
120    if not parser:
121        if log: log("All parser has failed.")
122        return None
123
124    if log: log("Using %s.%s" % (p.__module__, p.__name__))
125
126    converted_title = title = parser.title
127    if title and (not parser.charset):
128       try:
129          unicode(title, "ascii")
130       except UnicodeDecodeError:
131          parser.charset = DEFAULT_CHARSET
132
133    if parser.charset:
134       parser.charset = parser.charset.lower().replace("windows-", "cp")
135
136    if title and parser.charset and (
137          (parser.charset <> universal_charset) or
138          ((not charset) or (charset <> parser.charset))):
139       try:
140          if parser.meta_charset:
141             if log: log("   META charset   : %s" % parser.charset)
142          elif (not charset) or (charset <> parser.charset):
143             if log: log("   guessed charset: %s" % parser.charset)
144          if log: log("   current charset: %s" % universal_charset)
145          if log: log("   title          : %s" % title)
146          if parser.charset <> universal_charset:
147             try:
148                converted_title = unicode(title, parser.charset).encode(universal_charset)
149             except UnicodeError:
150                if log: log("   incorrect conversion from %s, converting from %s" % (parser.charset, DEFAULT_CHARSET))
151                converted_title = unicode(title, DEFAULT_CHARSET, "replace").encode(universal_charset, "replace")
152                parser.charset = DEFAULT_CHARSET
153          if log and (converted_title <> title): log("   converted title: %s" % converted_title)
154       except LookupError:
155          if log: log("   unknown charset: '%s'" % parser.charset)
156    else:
157       if log: log("   title          : %s" % title)
158
159    if title:
160       final_title = recode_entities(converted_title, universal_charset)
161       parts = [s.strip() for s in final_title.replace('\r', '').split('\n')]
162       final_title = ' '.join([s for s in parts if s])
163       if log and (final_title <> converted_title): log("   final title    : %s" % final_title)
164       parser.title = final_title
165
166    icon = parser.icon
167    if isinstance(icon, unicode):
168        try:
169            parser.icon = icon.encode('ascii')
170        except UnicodeEncodeError:
171            if parser.charset:
172                parser.icon = icon.encode(parser.charset)
173    return parser
174
175
176 def test():
177    import sys
178
179    l = len(sys.argv)
180    if l == 3:
181       filename = sys.argv[1]
182       charset = sys.argv[2]
183    elif l == 2:
184       filename = sys.argv[1]
185       charset = universal_charset
186    else:
187       sys.exit("Usage: %s filename [charset]" % sys.argv[0])
188
189    parser = parse_html(filename, charset, log=lambda s: sys.stdout.write(s + '\n'))
190    print "   refresh:", parser.refresh
191    print "   icon   :", parser.icon