]> git.phdru.name Git - bookmarks_db.git/blob - Robots/parse_html_html5.py
Parser could be None.
[bookmarks_db.git] / Robots / parse_html_html5.py
1 """
2     HTML Parser using html5.
3
4     Written by Broytman. Copyright (C) 2010 PhiloSoft Design
5 """
6
7 from html5lib import HTMLParser as HTML5Parser
8 from parse_html_util import HTMLParser
9
10
11 def parse_html(filename, charset=None, log=None):
12     parser = HTML5Parser()
13     fp = open(filename)
14     parser._parse(fp, encoding=charset, parseMeta=bool(charset))
15     fp.close()
16     html_tree = parser.tree.getDocument()
17
18     for node in html_tree.childNodes:
19         if (node.name == 'html') and (node.type != 3): # Skip DocType element
20             html = node
21             break
22     else:
23         html = None
24
25     if not html:
26         return None
27
28     for node in html.childNodes:
29         if node.name == 'head':
30             head = node
31             break
32     else:
33         head = None
34
35     meta_charset = False
36     title = None
37     refresh = None
38     icon = None
39
40     if head:
41         for node in head.childNodes:
42             if node.name == 'meta' and \
43                     ('http-equiv' in node.attributes) and \
44                     (node.attributes['http-equiv'] == 'content-type'):
45                 meta_content = node.attributes['content']
46                 if meta_content:
47                     try:
48                         meta_charset = \
49                             meta_content.lower().split('charset=')[1].split(';')[0]
50                     except IndexError:
51                         meta_charset = False
52                     else:
53                         break
54
55         for node in head.childNodes:
56             if node.name == 'title':
57                 if node.childNodes:
58                     title = node.childNodes[0].value
59                     break
60                 else:
61                     title = ''
62
63         if not charset:
64             charset = parser.tokenizer.stream.charEncoding[0]
65
66         if title and (charset or meta_charset):
67             title = title.encode(charset or meta_charset)
68
69         for node in head.childNodes:
70             if node.name == 'meta' and \
71                     ('http-equiv' in node.attributes) and \
72                     (node.attributes['http-equiv'] == 'refresh'):
73                 refresh = node.attributes['content']
74                 break
75
76         for node in head.childNodes:
77             if node.name == 'link' and \
78                     ('rel' in node.attributes) and \
79                     (node.attributes['rel'] in ('icon', 'shortcut icon')):
80                 icon = node.attributes['href']
81                 break
82
83     return HTMLParser(charset, meta_charset, title, refresh, icon)