3 # Copyright 2007 The Closure Linter Authors. All Rights Reserved.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS-IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 """Utilities for dealing with HTML."""
19 __author__ = ('robbyw@google.com (Robert Walker)')
28 class ScriptExtractor(htmllib.HTMLParser):
29 """Subclass of HTMLParser that extracts script contents from an HTML file.
31 Also inserts appropriate blank lines so that line numbers in the extracted
32 code match the line numbers in the original HTML.
36 """Initialize a ScriptExtractor."""
37 htmllib.HTMLParser.__init__(self, formatter.NullFormatter())
38 self._in_script = False
41 def start_script(self, attrs):
42 """Internal handler for the start of a script tag.
45 attrs: The attributes of the script tag, as a list of tuples.
47 for attribute in attrs:
48 if attribute[0].lower() == 'src':
49 # Skip script tags with a src specified.
51 self._in_script = True
54 """Internal handler for the end of a script tag."""
55 self._in_script = False
57 def handle_data(self, data):
58 """Internal handler for character data.
61 data: The character data from the HTML file.
64 # If the last line contains whitespace only, i.e. is just there to
65 # properly align a </script> tag, strip the whitespace.
66 if data.rstrip(' \t') != data.rstrip(' \t\n\r\f'):
67 data = data.rstrip(' \t')
70 self._AppendNewlines(data)
72 def handle_comment(self, data):
73 """Internal handler for HTML comments.
76 data: The text of the comment.
78 self._AppendNewlines(data)
80 def _AppendNewlines(self, data):
81 """Count the number of newlines in the given string and append them.
83 This ensures line numbers are correct for reported errors.
86 data: The data to count newlines in.
88 # We append 'x' to both sides of the string to ensure that splitlines
89 # gives us an accurate count.
90 for i in xrange(len(('x' + data + 'x').splitlines()) - 1):
93 def GetScriptLines(self):
94 """Return the extracted script lines.
97 The extracted script lines as a list of strings.
99 return self._text.splitlines()
102 def GetScriptLines(f):
103 """Extract script tag contents from the given HTML file.
109 Lines in the HTML file that are from script tags.
111 extractor = ScriptExtractor()
113 # The HTML parser chokes on text like Array.<!string>, so we patch
114 # that bug by replacing the < with < - escaping all text inside script
115 # tags would be better but it's a bit of a catch 22.
117 contents = re.sub(r'<([^\s\w/])',
118 lambda x: '<%s' % x.group(1),
121 extractor.feed(contents)
123 return extractor.GetScriptLines()
127 """Returns the string with HTML tags stripped.
133 The html string with all tags stripped. If there was a parse error, returns
134 the text successfully parsed so far.
136 # Brute force approach to stripping as much HTML as possible. If there is a
137 # parsing error, don't strip text before parse error position, and continue
143 strip = _HtmlStripper()
146 str = strip.get_output()
149 except HTMLParser.HTMLParseError, e:
150 final_text += str[:e.offset]
151 str = str[e.offset + 1:]
156 class _HtmlStripper(HTMLParser.HTMLParser):
157 """Simple class to strip tags from HTML.
159 Does so by doing nothing when encountering tags, and appending character data
160 to a buffer when that is encountered.
164 self.__output = cStringIO.StringIO()
166 def handle_data(self, d):
167 self.__output.write(d)
169 def get_output(self):
170 return self.__output.getvalue()