summaryrefslogtreecommitdiff
path: root/crocoite/html.py
blob: f891101a483f27365fd61893c7f2dab7735e5aec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# Copyright (c) 2017 crocoite contributors
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

"""
HTML helper
"""

# HTML void tags, see https://html.spec.whatwg.org/multipage/syntax.html#void-elements
voidTags = {'area',
        'base',
        'br',
        'col',
        'embed',
        'hr',
        'img',
        'input',
        'link',
        'meta',
        'param',
        'source',
        'track',
        'wbr'}

# source: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes
eventAttributes = {'onabort',
        'onautocomplete',
        'onautocompleteerror',
        'onblur',
        'oncancel',
        'oncanplay',
        'oncanplaythrough',
        'onchange',
        'onclick',
        'onclose',
        'oncontextmenu',
        'oncuechange',
        'ondblclick',
        'ondrag',
        'ondragend',
        'ondragenter',
        'ondragexit',
        'ondragleave',
        'ondragover',
        'ondragstart',
        'ondrop',
        'ondurationchange',
        'onemptied',
        'onended',
        'onerror',
        'onfocus',
        'oninput',
        'oninvalid',
        'onkeydown',
        'onkeypress',
        'onkeyup',
        'onload',
        'onloadeddata',
        'onloadedmetadata',
        'onloadstart',
        'onmousedown',
        'onmouseenter',
        'onmouseleave',
        'onmousemove',
        'onmouseout',
        'onmouseover',
        'onmouseup',
        'onmousewheel',
        'onpause',
        'onplay',
        'onplaying',
        'onprogress',
        'onratechange',
        'onreset',
        'onresize',
        'onscroll',
        'onseeked',
        'onseeking',
        'onselect',
        'onshow',
        'onsort',
        'onstalled',
        'onsubmit',
        'onsuspend',
        'ontimeupdate',
        'ontoggle',
        'onvolumechange',
        'onwaiting'}

from html5lib.treewalkers.base import TreeWalker
from html5lib.filters.base import Filter
from html5lib.serializer import HTMLSerializer
from html5lib import constants

class ChromeTreeWalker (TreeWalker):
    """
    Recursive html5lib TreeWalker for Google Chrome method DOM.getDocument
    """

    def recurse (self, node):
        name = node['nodeName']
        if name.startswith ('#'):
            if name == '#text':
                yield from self.text (node['nodeValue'])
            elif name == '#comment':
                yield self.comment (node['nodeValue'])
            elif name == '#document':
                for child in node.get ('children', []):
                    yield from self.recurse (child)
            else:
                assert False, name
        else:
            default_namespace = constants.namespaces["html"]

            attributes = node.get ('attributes', [])
            convertedAttr = {}
            for i in range (0, len (attributes), 2):
                convertedAttr[(default_namespace, attributes[i])] = attributes[i+1]

            children = node.get ('children', [])
            if name.lower() in voidTags and not children:
                yield from self.emptyTag (default_namespace, name, convertedAttr)
            else:
                yield self.startTag (default_namespace, name, convertedAttr)
                for child in node.get ('children', []):
                    yield from self.recurse (child)
                yield self.endTag ('', name)

    def __iter__ (self):
        assert self.tree['nodeName'] == '#document'
        return self.recurse (self.tree)

    def split (self):
        """
        Split response returned by DOM.getDocument(pierce=True) into independent documents
        """
        def recurse (node):
            contentDocument = node.get ('contentDocument')
            if contentDocument:
                assert contentDocument['nodeName'] == '#document'
                yield contentDocument
                yield from recurse (contentDocument)

            for child in node.get ('children', []):
                yield from recurse (child)

        if self.tree['nodeName'] == '#document':
            yield self.tree
        yield from recurse (self.tree)

class StripTagFilter (Filter):
    """
    Remove arbitrary tags
    """

    def __init__ (self, source, tags):
        Filter.__init__ (self, source)
        self.tags = set (map (str.lower, tags))

    def __iter__(self):
        delete = 0
        for token in Filter.__iter__(self):
            tokenType = token['type']
            if tokenType in {'StartTag', 'EmptyTag'}:
                if delete > 0 or token['name'].lower () in self.tags:
                    delete += 1
            if delete == 0:
                yield token
            if tokenType == 'EndTag' and delete > 0:
                delete -= 1

class StripAttributeFilter (Filter):
    """
    Remove arbitrary HTML attributes
    """

    def __init__ (self, source, attributes):
        Filter.__init__ (self, source)
        self.attributes = set (map (str.lower, attributes))

    def __iter__(self):
        default_namespace = constants.namespaces["html"]
        for token in Filter.__iter__(self):
            data = token.get ('data')
            if data and token['type'] in {'StartTag', 'EmptyTag'}:
                newdata = {}
                for (namespace, k), v in data.items ():
                    if k.lower () not in self.attributes:
                        newdata[(namespace, k)] = v
                token['data'] = newdata
            yield token