]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html.py
25b3bb04c55f654c9620bf4682fc0a6cec313eb0
[bookmarks_db.git] / Robots / parse_html.py
1 #! /usr/bin/env python
2 """
3    HTML Parser
4
5    Written by BroytMann. Copyright (C) 1997-2007 PhiloSoft Design
6 """
7
8 from m_lib.defenc import default_encoding
9 current_charset = default_encoding.replace("windows-", "cp")
10 DEFAULT_CHARSET = "cp1251" # Stupid default for Russian Cyrillic
11
12 from HTMLParser import HTMLParseError
13 from m_lib.net.www.html import HTMLParser as _HTMLParser
14
15
16 class HTMLHeadDone(Exception): pass
17
18
19 class HTMLParser(_HTMLParser):
20    def __init__(self, charset=None):
21       _HTMLParser.__init__(self)
22       self.charset = charset
23       self.meta_charset = 0
24       self.title = ''
25       self.refresh = ''
26       self.icon = None
27
28    def end_head(self):
29       raise HTMLHeadDone()
30
31
32    def do_meta(self, attrs):
33       http_equiv = ""
34       content = ""
35
36       for attrname, value in attrs:
37          if value:
38             value = value.strip()
39             if attrname == 'http-equiv':
40                http_equiv = value.lower()
41             elif attrname == 'content':
42                content = value
43
44       if (not self.charset) and (http_equiv == "content-type"):
45          try:
46             # extract charset from "text/html; foo; charset=UTF-8; bar;"
47             self.charset = content.lower().split('charset=')[1].split(';')[0]
48             self.meta_charset = 1 # Remember that the charset was retrieved from
49                                   # META tag, not from the Content-Type header
50          except IndexError:
51             pass
52
53       if http_equiv == "refresh":
54          self.refresh = content
55
56
57    def start_title(self, attrs):
58       self.accumulator = ''
59
60    def end_title(self):
61       if not self.title: # use only the first title
62          self.title = self.accumulator
63
64
65    def do_link(self, attrs):
66       has_icon = False
67       href = None
68
69       for attrname, value in attrs:
70          if value:
71             value = value.strip().lower()
72             if (attrname == 'rel') and (value in ('icon', 'shortcut icon')):
73                has_icon = True
74             elif attrname == 'href':
75                href = value
76
77       if has_icon:
78          self.icon = href
79       else:
80          self.icon = None
81
82
83 import re
84 entity_re = re.compile("(&#[0-9]+;)")
85
86 def recode_entities(title, charset):
87    output = []
88    for part in entity_re.split(title):
89       if entity_re.match(part):
90          part = unichr(int(part[2:-1])).encode(charset, "replace")
91       output.append(part)
92
93    return ''.join(output)
94
95
96 def parse_html(filename, charset=None, log=None):
97    if charset:
98       try:
99          codecs.lookup(charset) # In case of unknown charset...
100       except (ValueError, LookupError):
101          charset = None         # ...try charset from HTML
102
103    infile = open(filename, 'r')
104    parser = HTMLParser(charset)
105
106    for line in infile:
107       try:
108          parser.feed(line)
109       except (HTMLParseError, HTMLHeadDone):
110          break
111
112    infile.close()
113
114    try:
115       parser.close()
116    except (HTMLParseError, HTMLHeadDone):
117       pass
118
119    title = parser.title
120
121    if not parser.charset:
122       try:
123          unicode(title, "ascii")
124       except UnicodeDecodeError:
125          parser.charset = DEFAULT_CHARSET
126
127    if parser.charset:
128       parser.charset = parser.charset.replace("windows-", "cp").lower()
129
130    if parser.charset and (parser.charset <> current_charset):
131       try:
132          if parser.meta_charset:
133             if log: log("   META charset   : %s" % parser.charset)
134          else:
135             if log: log("   charset        : %s" % parser.charset)
136          if log: log("   title          : %s" % title)
137          title = unicode(title, parser.charset, "replace").encode(current_charset, "replace")
138          if log: log("   current charset: %s" % current_charset)
139          if log: log("   converted title: %s" % title)
140       except LookupError:
141          if log: log("   unknown charset: `%s' or `%s'" % (parser.charset, current_charset))
142
143    parser.title = recode_entities(title, current_charset)
144    return parser
145
146
147 if __name__ == '__main__':
148    parser = parse_html(sys.argv[1])
149    print parser.charset
150    print parser.title
151    print parser.refresh
152    print parser.icon