| 1 |
from __future__ import absolute_import |
| 2 |
|
| 3 |
import codecs |
| 4 |
import copy |
| 5 |
import re |
| 6 |
|
| 7 |
from ._form import parse_forms |
| 8 |
from ._headersutil import is_html as _is_html |
| 9 |
from ._headersutil import split_header_words |
| 10 |
from ._rfc3986 import clean_url, urljoin |
| 11 |
from .polyglot import is_string |
| 12 |
|
| 13 |
DEFAULT_ENCODING = "utf-8" |
| 14 |
_encoding_pats = ( |
| 15 |
|
| 16 |
r'<\?[^<>]+encoding\s*=\s*[\'"](.*?)[\'"][^<>]*>', |
| 17 |
|
| 18 |
r'''<meta\s+charset=['"]([-_a-z0-9]+)['"][^<>]*>(?:\s*</meta>){0,1}''', |
| 19 |
|
| 20 |
r'''<meta\s+?[^<>]*?content\s*=\s*['"][^'"]*?charset=([-_a-z0-9]+)[^'"]*?['"][^<>]*>(?:\s*</meta>){0,1}''', |
| 21 |
) |
| 22 |
|
| 23 |
|
| 24 |
def compile_pats(binary): |
| 25 |
for raw in _encoding_pats: |
| 26 |
if binary: |
| 27 |
raw = raw.encode('ascii') |
| 28 |
yield re.compile(raw, flags=re.IGNORECASE) |
| 29 |
|
| 30 |
|
| 31 |
class LazyEncodingPats(object): |
| 32 |
|
| 33 |
def __call__(self, binary=False): |
| 34 |
attr = 'binary_pats' if binary else 'unicode_pats' |
| 35 |
pats = getattr(self, attr, None) |
| 36 |
if pats is None: |
| 37 |
pats = tuple(compile_pats(binary)) |
| 38 |
setattr(self, attr, pats) |
| 39 |
for pat in pats: |
| 40 |
yield pat |
| 41 |
|
| 42 |
|
| 43 |
lazy_encoding_pats = LazyEncodingPats() |
| 44 |
|
| 45 |
|
| 46 |
def find_declared_encoding(raw, limit=50*1024): |
| 47 |
prefix = raw[:limit] |
| 48 |
is_binary = isinstance(raw, bytes) |
| 49 |
for pat in lazy_encoding_pats(is_binary): |
| 50 |
m = pat.search(prefix) |
| 51 |
if m is not None: |
| 52 |
ans = m.group(1) |
| 53 |
if is_binary: |
| 54 |
ans = ans.decode('ascii', 'replace') |
| 55 |
return ans |
| 56 |
|
| 57 |
|
| 58 |
def elem_text(elem): |
| 59 |
if elem.text: |
| 60 |
yield elem.text |
| 61 |
for child in elem: |
| 62 |
for text in elem_text(child): |
| 63 |
yield text |
| 64 |
if child.tail: |
| 65 |
yield child.tail |
| 66 |
|
| 67 |
|
| 68 |
def iterlinks(root, base_url): |
| 69 |
link_tags = {"a": "href", "area": "href", "iframe": "src"} |
| 70 |
for tag in root.iter('*'): |
| 71 |
if not is_string(tag.tag): |
| 72 |
continue |
| 73 |
q = tag.tag.lower() |
| 74 |
attr = link_tags.get(q) |
| 75 |
if attr is not None: |
| 76 |
val = tag.get(attr) |
| 77 |
if val: |
| 78 |
url = clean_url(val) |
| 79 |
yield Link(base_url, url, |
| 80 |
compress_whitespace(u''.join(elem_text(tag))), q, |
| 81 |
tag.items()) |
| 82 |
elif q == 'base': |
| 83 |
href = tag.get('href') |
| 84 |
if href: |
| 85 |
base_url = href |
| 86 |
|
| 87 |
|
| 88 |
def compress_whitespace(text): |
| 89 |
return re.sub(r'\s+', ' ', text or '').strip() |
| 90 |
|
| 91 |
|
| 92 |
def get_encoding_from_response(response, verify=True): |
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
if response: |
| 97 |
for ct in response.info().getheaders("content-type"): |
| 98 |
for k, v in split_header_words([ct])[0]: |
| 99 |
if k == "charset": |
| 100 |
if not verify: |
| 101 |
return v |
| 102 |
try: |
| 103 |
codecs.lookup(v) |
| 104 |
return v |
| 105 |
except LookupError: |
| 106 |
continue |
| 107 |
|
| 108 |
|
| 109 |
class EncodingFinder: |
| 110 |
def __init__(self, default_encoding): |
| 111 |
self._default_encoding = default_encoding |
| 112 |
|
| 113 |
def encoding(self, response): |
| 114 |
return get_encoding_from_response(response) or self._default_encoding |
| 115 |
|
| 116 |
|
| 117 |
class ResponseTypeFinder: |
| 118 |
def __init__(self, allow_xhtml): |
| 119 |
self._allow_xhtml = allow_xhtml |
| 120 |
|
| 121 |
def is_html(self, response, encoding): |
| 122 |
ct_hdrs = response.info().getheaders("content-type") |
| 123 |
url = response.geturl() |
| 124 |
|
| 125 |
return _is_html(ct_hdrs, url, self._allow_xhtml) |
| 126 |
|
| 127 |
|
| 128 |
class Link: |
| 129 |
''' |
| 130 |
A link in a HTML document |
| 131 |
|
| 132 |
:ivar absolute_url: The absolutized link URL |
| 133 |
:ivar url: The link URL |
| 134 |
:ivar base_url: The base URL against which this link is resolved |
| 135 |
:ivar text: The link text |
| 136 |
:ivar tag: The link tag name |
| 137 |
:ivar attrs: The tag attributes |
| 138 |
|
| 139 |
''' |
| 140 |
def __init__(self, base_url, url, text, tag, attrs): |
| 141 |
assert None not in [url, tag, attrs] |
| 142 |
self.base_url = base_url |
| 143 |
self.absolute_url = urljoin(base_url, url) |
| 144 |
self.url, self.text, self.tag, self.attrs = url, text, tag, attrs |
| 145 |
self.text = self.text |
| 146 |
|
| 147 |
def __eq__(self, other): |
| 148 |
try: |
| 149 |
for name in "url", "text", "tag": |
| 150 |
if getattr(self, name) != getattr(other, name): |
| 151 |
return False |
| 152 |
if dict(self.attrs) != dict(other.attrs): |
| 153 |
return False |
| 154 |
except AttributeError: |
| 155 |
return False |
| 156 |
return True |
| 157 |
|
| 158 |
def __ne__(self, other): |
| 159 |
return not self.__eq__(other) |
| 160 |
|
| 161 |
def __repr__(self): |
| 162 |
return "Link(base_url=%r, url=%r, text=%r, tag=%r, attrs=%r)" % ( |
| 163 |
self.base_url, self.url, self.text, self.tag, self.attrs) |
| 164 |
|
| 165 |
|
| 166 |
def content_parser(data, |
| 167 |
url=None, |
| 168 |
response_info=None, |
| 169 |
transport_encoding=None, |
| 170 |
default_encoding=DEFAULT_ENCODING, |
| 171 |
is_html=True): |
| 172 |
''' |
| 173 |
Parse data (a bytes object) into an etree representation such as |
| 174 |
:py:mod:`xml.etree.ElementTree` or `lxml.etree` |
| 175 |
|
| 176 |
:param bytes data: The data to parse |
| 177 |
:param url: The URL of the document being parsed or None |
| 178 |
:param response_info: Information about the document |
| 179 |
(contains all HTTP headers as :class:`HTTPMessage`) |
| 180 |
:param transport_encoding: The character encoding for the document being |
| 181 |
parsed as specified in the HTTP headers or None. |
| 182 |
:param default_encoding: The character encoding to use if no encoding |
| 183 |
could be detected and no transport_encoding is specified |
| 184 |
:param is_html: If the document is to be parsed as HTML. |
| 185 |
''' |
| 186 |
if not is_html: |
| 187 |
return |
| 188 |
try: |
| 189 |
from html5_parser import parse |
| 190 |
except Exception: |
| 191 |
from html5lib import parse |
| 192 |
kw = {'namespaceHTMLElements': False} |
| 193 |
if transport_encoding and isinstance(data, bytes): |
| 194 |
kw['transport_encoding'] = transport_encoding |
| 195 |
return parse(data, **kw) |
| 196 |
else: |
| 197 |
return parse(data, transport_encoding=transport_encoding) |
| 198 |
|
| 199 |
|
| 200 |
def get_title(root): |
| 201 |
for title in root.iter('title'): |
| 202 |
text = compress_whitespace(title.text) |
| 203 |
if text: |
| 204 |
return text |
| 205 |
|
| 206 |
|
| 207 |
lazy = object() |
| 208 |
|
| 209 |
|
| 210 |
class Factory: |
| 211 |
"""Factory for forms, links, etc. |
| 212 |
|
| 213 |
This interface may expand in future. |
| 214 |
|
| 215 |
Public methods: |
| 216 |
|
| 217 |
set_request_class(request_class) |
| 218 |
set_response(response) |
| 219 |
forms() |
| 220 |
links() |
| 221 |
|
| 222 |
Public attributes: |
| 223 |
|
| 224 |
Note that accessing these attributes may raise ParseError. |
| 225 |
|
| 226 |
encoding: string specifying the encoding of response if it contains a text |
| 227 |
document (this value is left unspecified for documents that do not have |
| 228 |
an encoding, e.g. an image file) |
| 229 |
is_html: true if response contains an HTML document (XHTML may be |
| 230 |
regarded as HTML too) |
| 231 |
title: page title, or None if no title or not HTML |
| 232 |
global_form: form object containing all controls that are not descendants |
| 233 |
of any FORM element, or None if the forms_factory does not support |
| 234 |
supplying a global form |
| 235 |
|
| 236 |
""" |
| 237 |
|
| 238 |
def __init__( |
| 239 |
self, |
| 240 |
default_encoding=DEFAULT_ENCODING, |
| 241 |
allow_xhtml=False, ): |
| 242 |
""" |
| 243 |
|
| 244 |
Pass keyword arguments only. |
| 245 |
|
| 246 |
""" |
| 247 |
self._encoding_finder = EncodingFinder(default_encoding) |
| 248 |
self.form_encoding = default_encoding |
| 249 |
self._response_type_finder = ResponseTypeFinder( |
| 250 |
allow_xhtml=allow_xhtml) |
| 251 |
self._content_parser = content_parser |
| 252 |
self._current_forms = self._current_links = self._current_title = lazy |
| 253 |
self._current_global_form = self._root = lazy |
| 254 |
self._raw_data = b'' |
| 255 |
self.is_html, self.encoding = False, DEFAULT_ENCODING |
| 256 |
|
| 257 |
self.set_response(None) |
| 258 |
|
| 259 |
def set_content_parser(self, val): |
| 260 |
self._content_parser = val |
| 261 |
|
| 262 |
def set_request_class(self, request_class): |
| 263 |
"""Set request class (mechanize.Request by default). |
| 264 |
|
| 265 |
HTMLForm instances returned by .forms() will return instances of this |
| 266 |
class when .click()ed. |
| 267 |
|
| 268 |
""" |
| 269 |
self._request_class = request_class |
| 270 |
|
| 271 |
def set_response(self, response): |
| 272 |
"""Set response. |
| 273 |
|
| 274 |
The response must either be None or implement the same interface as |
| 275 |
objects returned by mechanize.urlopen(). |
| 276 |
|
| 277 |
""" |
| 278 |
self._response = copy.copy(response) |
| 279 |
self._current_forms = self._current_links = self._current_title = lazy |
| 280 |
self._current_global_form = self._root = lazy |
| 281 |
self.encoding = self._encoding_finder.encoding(self._response) |
| 282 |
self.is_html = self._response_type_finder.is_html( |
| 283 |
self._response, self.encoding) if self._response else False |
| 284 |
|
| 285 |
@property |
| 286 |
def root(self): |
| 287 |
if self._root is lazy: |
| 288 |
response = self._response |
| 289 |
raw = self._response.read() if self._response else b'' |
| 290 |
default_encoding = self._encoding_finder._default_encoding |
| 291 |
transport_encoding = get_encoding_from_response(response, verify=False) |
| 292 |
declared_encoding = find_declared_encoding(raw) |
| 293 |
self.form_encoding = declared_encoding or transport_encoding or default_encoding |
| 294 |
self._root = self._content_parser( |
| 295 |
raw, |
| 296 |
url=response.geturl() if response else None, |
| 297 |
response_info=response.info() if response else None, |
| 298 |
default_encoding=default_encoding, |
| 299 |
is_html=self.is_html, |
| 300 |
transport_encoding=transport_encoding) |
| 301 |
return self._root |
| 302 |
|
| 303 |
@property |
| 304 |
def title(self): |
| 305 |
if self._current_title is lazy: |
| 306 |
self._current_title = get_title( |
| 307 |
self.root) if self.root is not None else None |
| 308 |
return self._current_title or u'' |
| 309 |
|
| 310 |
@property |
| 311 |
def global_form(self): |
| 312 |
if self._current_global_form is lazy: |
| 313 |
self.forms() |
| 314 |
return self._current_global_form |
| 315 |
|
| 316 |
def forms(self): |
| 317 |
""" Return tuple of HTMLForm-like objects. """ |
| 318 |
|
| 319 |
if self._current_forms is lazy: |
| 320 |
self._current_forms, self._current_global_form = self._get_forms() |
| 321 |
return self._current_forms |
| 322 |
|
| 323 |
def links(self): |
| 324 |
"""Return tuple of mechanize.Link-like objects. """ |
| 325 |
if self._current_links is lazy: |
| 326 |
self._current_links = self._get_links() |
| 327 |
return self._get_links() |
| 328 |
|
| 329 |
def _get_links(self): |
| 330 |
if self.root is None: |
| 331 |
return () |
| 332 |
return tuple(iterlinks(self.root, self._response.geturl())) |
| 333 |
|
| 334 |
def _get_forms(self): |
| 335 |
if self.root is None: |
| 336 |
return (), None |
| 337 |
return parse_forms(self.root, |
| 338 |
self._response.geturl(), self._request_class, encoding=self.form_encoding) |