| 1 |
"""Stateful programmatic WWW navigation, after Perl's WWW::Mechanize. |
| 2 |
|
| 3 |
Copyright 2003-2006 John J. Lee <[email protected]> |
| 4 |
Copyright 2003 Andy Lester (original Perl code) |
| 5 |
|
| 6 |
This code is free software; you can redistribute it and/or modify it |
| 7 |
under the terms of the BSD or ZPL 2.1 licenses (see the file LICENSE |
| 8 |
included with the distribution). |
| 9 |
|
| 10 |
""" |
| 11 |
from __future__ import absolute_import |
| 12 |
|
| 13 |
import copy |
| 14 |
import os |
| 15 |
import re |
| 16 |
|
| 17 |
from . import _request, _response, _rfc3986, _sockettimeout, _urllib2_fork |
| 18 |
from ._clientcookie import Cookie |
| 19 |
from ._headersutil import normalize_header_name |
| 20 |
from ._html import Factory |
| 21 |
from ._useragent import UserAgentBase |
| 22 |
from .polyglot import pathname2url, HTTPError, is_string, iteritems |
| 23 |
from ._response import make_response |
| 24 |
|
| 25 |
|
| 26 |
class BrowserStateError(Exception): |
| 27 |
pass |
| 28 |
|
| 29 |
|
| 30 |
class LinkNotFoundError(Exception): |
| 31 |
pass |
| 32 |
|
| 33 |
|
| 34 |
class FormNotFoundError(Exception): |
| 35 |
pass |
| 36 |
|
| 37 |
|
| 38 |
def sanepathname2url(path): |
| 39 |
urlpath = pathname2url(path) |
| 40 |
if os.name == "nt" and urlpath.startswith("///"): |
| 41 |
urlpath = urlpath[2:] |
| 42 |
|
| 43 |
return urlpath |
| 44 |
|
| 45 |
|
| 46 |
class History: |
| 47 |
""" |
| 48 |
|
| 49 |
Though this will become public, the implied interface is not yet stable. |
| 50 |
|
| 51 |
""" |
| 52 |
|
| 53 |
def __init__(self): |
| 54 |
self._history = [] |
| 55 |
|
| 56 |
def add(self, request, response): |
| 57 |
self._history.append((request, response)) |
| 58 |
|
| 59 |
def back(self, n, _response): |
| 60 |
response = _response |
| 61 |
while n > 0 or response is None: |
| 62 |
try: |
| 63 |
request, response = self._history.pop() |
| 64 |
except IndexError: |
| 65 |
raise BrowserStateError("already at start of history") |
| 66 |
n -= 1 |
| 67 |
return request, response |
| 68 |
|
| 69 |
def clear(self): |
| 70 |
del self._history[:] |
| 71 |
|
| 72 |
def close(self): |
| 73 |
for request, response in self._history: |
| 74 |
if response is not None: |
| 75 |
response.close() |
| 76 |
del self._history[:] |
| 77 |
|
| 78 |
def __copy__(self): |
| 79 |
ans = self.__class__() |
| 80 |
ans._history = self._history[:] |
| 81 |
return ans |
| 82 |
|
| 83 |
|
| 84 |
class HTTPRefererProcessor(_urllib2_fork.BaseHandler): |
| 85 |
def http_request(self, request): |
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
if hasattr(request, "redirect_dict"): |
| 92 |
request = self.parent._add_referer_header( |
| 93 |
request, origin_request=False) |
| 94 |
return request |
| 95 |
|
| 96 |
https_request = http_request |
| 97 |
|
| 98 |
|
| 99 |
class Browser(UserAgentBase): |
| 100 |
"""Browser-like class with support for history, forms and links. |
| 101 |
|
| 102 |
:class:`BrowserStateError` is raised whenever the browser is in the wrong |
| 103 |
state to complete the requested operation - e.g., when :meth:`back()` is |
| 104 |
called when the browser history is empty, or when :meth:`follow_link()` is |
| 105 |
called when the current response does not contain HTML data. |
| 106 |
|
| 107 |
Public attributes: |
| 108 |
|
| 109 |
request: current request (:class:`mechanize.Request`) |
| 110 |
|
| 111 |
form: currently selected form (see :meth:`select_form()`) |
| 112 |
|
| 113 |
:param history: object implementing the :class:`mechanize.History` |
| 114 |
interface. Note this interface is still experimental |
| 115 |
and may change in future. This object is owned |
| 116 |
by the browser instance and must not be shared |
| 117 |
among browsers. |
| 118 |
:param request_class: Request class to use. Defaults to |
| 119 |
:class:`mechanize.Request` |
| 120 |
:param content_parser: A function that is responsible for parsing |
| 121 |
received html/xhtml content. See the builtin |
| 122 |
:func:`mechanize._html.content_parser()` function for details |
| 123 |
on the interface this function must support. |
| 124 |
:param factory_class: HTML Factory class to use. Defaults to |
| 125 |
:class:`mechanize.Factory` |
| 126 |
|
| 127 |
""" |
| 128 |
|
| 129 |
handler_classes = copy.copy(UserAgentBase.handler_classes) |
| 130 |
handler_classes["_referer"] = HTTPRefererProcessor |
| 131 |
default_features = copy.copy(UserAgentBase.default_features) |
| 132 |
default_features.append("_referer") |
| 133 |
|
| 134 |
def __init__( |
| 135 |
self, |
| 136 |
history=None, |
| 137 |
request_class=None, |
| 138 |
content_parser=None, |
| 139 |
factory_class=Factory, |
| 140 |
allow_xhtml=False, ): |
| 141 |
""" |
| 142 |
Only named arguments should be passed to this constructor. |
| 143 |
|
| 144 |
""" |
| 145 |
self._handle_referer = True |
| 146 |
|
| 147 |
if history is None: |
| 148 |
history = History() |
| 149 |
self._history = history |
| 150 |
|
| 151 |
if request_class is None: |
| 152 |
request_class = _request.Request |
| 153 |
|
| 154 |
factory = factory_class(allow_xhtml=allow_xhtml) |
| 155 |
factory.set_request_class(request_class) |
| 156 |
if content_parser is not None: |
| 157 |
factory.set_content_parser(content_parser) |
| 158 |
self._factory = factory |
| 159 |
self.request_class = request_class |
| 160 |
|
| 161 |
self.request = None |
| 162 |
self._set_response(None, False) |
| 163 |
|
| 164 |
|
| 165 |
UserAgentBase.__init__(self) |
| 166 |
|
| 167 |
def __copy__(self): |
| 168 |
''' |
| 169 |
Clone this browser instance. The clone will share the same, thread-safe |
| 170 |
cookie jar, and have all the same handlers/settings, but will not share |
| 171 |
any other state, making it safe to use in another thread. |
| 172 |
''' |
| 173 |
ans = self.__class__() |
| 174 |
self._copy_state(ans) |
| 175 |
ans._handle_referer = self._handle_referer |
| 176 |
for attr in ('_response_type_finder', '_encoding_finder', |
| 177 |
'_content_parser'): |
| 178 |
setattr(ans._factory, attr, getattr(self._factory, attr)) |
| 179 |
ans.request_class = self.request_class |
| 180 |
ans._history = copy.copy(self._history) |
| 181 |
return ans |
| 182 |
|
| 183 |
def close(self): |
| 184 |
UserAgentBase.close(self) |
| 185 |
if self._response is not None: |
| 186 |
self._response.close() |
| 187 |
if self._history is not None: |
| 188 |
self._history.close() |
| 189 |
self._history = None |
| 190 |
|
| 191 |
|
| 192 |
self.form = None |
| 193 |
self.request = self._response = None |
| 194 |
self.request = self.response = self.set_response = None |
| 195 |
self.geturl = self.reload = self.back = None |
| 196 |
self.clear_history = self.set_cookie = self.links = self.forms = None |
| 197 |
self.viewing_html = self.encoding = self.title = None |
| 198 |
self.select_form = self.click = self.submit = self.click_link = None |
| 199 |
self.follow_link = self.find_link = None |
| 200 |
|
| 201 |
def set_handle_referer(self, handle): |
| 202 |
"""Set whether to add Referer header to each request.""" |
| 203 |
self._set_handler("_referer", handle) |
| 204 |
self._handle_referer = bool(handle) |
| 205 |
|
| 206 |
def _add_referer_header(self, request, origin_request=True): |
| 207 |
if self.request is None: |
| 208 |
return request |
| 209 |
scheme = request.get_type() |
| 210 |
original_scheme = self.request.get_type() |
| 211 |
if scheme not in ["http", "https"]: |
| 212 |
return request |
| 213 |
if not origin_request and not self.request.has_header("Referer"): |
| 214 |
return request |
| 215 |
|
| 216 |
if (self._handle_referer and original_scheme in ["http", "https"] and |
| 217 |
not (original_scheme == "https" and scheme != "https")): |
| 218 |
|
| 219 |
parts = _rfc3986.urlsplit(self.request.get_full_url()) |
| 220 |
parts = parts[:-1] + (None, ) |
| 221 |
referer = _rfc3986.urlunsplit(parts) |
| 222 |
request.add_unredirected_header("Referer", referer) |
| 223 |
return request |
| 224 |
|
| 225 |
def open_novisit(self, |
| 226 |
url_or_request, |
| 227 |
data=None, |
| 228 |
timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT): |
| 229 |
"""Open a URL without visiting it. |
| 230 |
|
| 231 |
Browser state (including request, response, history, forms and links) |
| 232 |
is left unchanged by calling this function. |
| 233 |
|
| 234 |
The interface is the same as for :meth:`open()`. |
| 235 |
|
| 236 |
This is useful for things like fetching images. |
| 237 |
|
| 238 |
See also :meth:`retrieve()` |
| 239 |
|
| 240 |
""" |
| 241 |
return self._mech_open( |
| 242 |
url_or_request, data, visit=False, timeout=timeout) |
| 243 |
|
| 244 |
def open(self, |
| 245 |
url_or_request, |
| 246 |
data=None, |
| 247 |
timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT): |
| 248 |
''' |
| 249 |
Open a URL. Loads the page so that you can subsequently use |
| 250 |
:meth:`forms()`, :meth:`links()`, etc. on it. |
| 251 |
|
| 252 |
:param url_or_request: Either a URL or a :class:`mechanize.Request` |
| 253 |
:param dict data: data to send with a POST request |
| 254 |
:param timeout: Timeout in seconds |
| 255 |
:return: A :class:`mechanize.Response` object |
| 256 |
''' |
| 257 |
return self._mech_open(url_or_request, data, timeout=timeout) |
| 258 |
|
| 259 |
def _mech_open(self, |
| 260 |
url, |
| 261 |
data=None, |
| 262 |
update_history=True, |
| 263 |
visit=None, |
| 264 |
timeout=_sockettimeout._GLOBAL_DEFAULT_TIMEOUT): |
| 265 |
try: |
| 266 |
url.get_full_url |
| 267 |
except AttributeError: |
| 268 |
|
| 269 |
scheme, authority = _rfc3986.urlsplit(url)[:2] |
| 270 |
if scheme is None: |
| 271 |
|
| 272 |
if self._response is None: |
| 273 |
raise BrowserStateError("can't fetch relative reference: " |
| 274 |
"not viewing any document") |
| 275 |
url = _rfc3986.urljoin(self._response.geturl(), url) |
| 276 |
|
| 277 |
request = self._request(url, data, visit, timeout) |
| 278 |
visit = request.visit |
| 279 |
if visit is None: |
| 280 |
visit = True |
| 281 |
|
| 282 |
if visit: |
| 283 |
self._visit_request(request, update_history) |
| 284 |
|
| 285 |
success = True |
| 286 |
try: |
| 287 |
response = UserAgentBase.open(self, request, data) |
| 288 |
except HTTPError as error: |
| 289 |
success = False |
| 290 |
if error.fp is None: |
| 291 |
raise |
| 292 |
response = error |
| 293 |
|
| 294 |
|
| 295 |
|
| 296 |
|
| 297 |
|
| 298 |
|
| 299 |
|
| 300 |
|
| 301 |
|
| 302 |
|
| 303 |
|
| 304 |
|
| 305 |
|
| 306 |
if visit: |
| 307 |
self._set_response(response, False) |
| 308 |
response = copy.copy(self._response) |
| 309 |
elif response is not None: |
| 310 |
response = _response.upgrade_response(response) |
| 311 |
|
| 312 |
if not success: |
| 313 |
raise response |
| 314 |
return response |
| 315 |
|
| 316 |
def __str__(self): |
| 317 |
text = [] |
| 318 |
text.append("<%s " % self.__class__.__name__) |
| 319 |
if self._response: |
| 320 |
text.append("visiting %s" % self._response.geturl()) |
| 321 |
else: |
| 322 |
text.append("(not visiting a URL)") |
| 323 |
if self.form: |
| 324 |
text.append("\n selected form:\n %s\n" % str(self.form)) |
| 325 |
text.append(">") |
| 326 |
return "".join(text) |
| 327 |
|
| 328 |
def response(self): |
| 329 |
"""Return a copy of the current response. |
| 330 |
|
| 331 |
The returned object has the same interface as the object returned by |
| 332 |
:meth:`.open()` |
| 333 |
|
| 334 |
""" |
| 335 |
return copy.copy(self._response) |
| 336 |
|
| 337 |
def open_local_file(self, filename): |
| 338 |
path = sanepathname2url(os.path.abspath(filename)) |
| 339 |
url = 'file://' + path |
| 340 |
return self.open(url) |
| 341 |
|
| 342 |
def set_response(self, response): |
| 343 |
"""Replace current response with (a copy of) response. |
| 344 |
|
| 345 |
response may be None. |
| 346 |
|
| 347 |
This is intended mostly for HTML-preprocessing. |
| 348 |
""" |
| 349 |
self._set_response(response, True) |
| 350 |
|
| 351 |
def _set_response(self, response, close_current): |
| 352 |
|
| 353 |
if not (response is None or |
| 354 |
(hasattr(response, "info") and hasattr(response, "geturl") and |
| 355 |
hasattr(response, "read"))): |
| 356 |
raise ValueError("not a response object") |
| 357 |
|
| 358 |
self.form = None |
| 359 |
if response is not None: |
| 360 |
response = _response.upgrade_response(response) |
| 361 |
if close_current and self._response is not None: |
| 362 |
self._response.close() |
| 363 |
self._response = response |
| 364 |
self._factory.set_response(response) |
| 365 |
|
| 366 |
def visit_response(self, response, request=None): |
| 367 |
"""Visit the response, as if it had been :meth:`open()` ed. |
| 368 |
|
| 369 |
Unlike :meth:`set_response()`, this updates history rather than |
| 370 |
replacing the current response. |
| 371 |
""" |
| 372 |
if request is None: |
| 373 |
request = _request.Request(response.geturl()) |
| 374 |
self._visit_request(request, True) |
| 375 |
self._set_response(response, False) |
| 376 |
|
| 377 |
def _visit_request(self, request, update_history): |
| 378 |
if self._response is not None: |
| 379 |
self._response.close() |
| 380 |
if self.request is not None and update_history: |
| 381 |
self._history.add(self.request, self._response) |
| 382 |
self._response = None |
| 383 |
|
| 384 |
|
| 385 |
self.request = request |
| 386 |
|
| 387 |
def set_html(self, html, url="http://example.com/"): |
| 388 |
"""Set the response to dummy with given HTML, and URL if given. |
| 389 |
|
| 390 |
Allows you to then parse that HTML, especially to extract forms |
| 391 |
information. If no URL was given then the default is "example.com". |
| 392 |
""" |
| 393 |
response = make_response(html, [("Content-type", "text/html")], url) |
| 394 |
self._set_response(response, True) |
| 395 |
|
| 396 |
def geturl(self): |
| 397 |
"""Get URL of current document.""" |
| 398 |
if self._response is None: |
| 399 |
raise BrowserStateError("not viewing any document") |
| 400 |
return self._response.geturl() |
| 401 |
|
| 402 |
def reload(self): |
| 403 |
"""Reload current document, and return response object.""" |
| 404 |
if self.request is None: |
| 405 |
raise BrowserStateError("no URL has yet been .open()ed") |
| 406 |
if self._response is not None: |
| 407 |
self._response.close() |
| 408 |
return self._mech_open(self.request, update_history=False) |
| 409 |
|
| 410 |
def back(self, n=1): |
| 411 |
"""Go back n steps in history, and return response object. |
| 412 |
|
| 413 |
n: go back this number of steps (default 1 step) |
| 414 |
|
| 415 |
""" |
| 416 |
if self._response is not None: |
| 417 |
self._response.close() |
| 418 |
self.request, response = self._history.back(n, self._response) |
| 419 |
self.set_response(response) |
| 420 |
if not response.read_complete: |
| 421 |
return self.reload() |
| 422 |
return copy.copy(response) |
| 423 |
|
| 424 |
def clear_history(self): |
| 425 |
self._history.clear() |
| 426 |
|
| 427 |
def set_cookie(self, cookie_string): |
| 428 |
"""Set a cookie. |
| 429 |
|
| 430 |
Note that it is NOT necessary to call this method under ordinary |
| 431 |
circumstances: cookie handling is normally entirely automatic. The |
| 432 |
intended use case is rather to simulate the setting of a cookie by |
| 433 |
client script in a web page (e.g. JavaScript). In that case, use of |
| 434 |
this method is necessary because mechanize currently does not support |
| 435 |
JavaScript, VBScript, etc. |
| 436 |
|
| 437 |
The cookie is added in the same way as if it had arrived with the |
| 438 |
current response, as a result of the current request. This means that, |
| 439 |
for example, if it is not appropriate to set the cookie based on the |
| 440 |
current request, no cookie will be set. |
| 441 |
|
| 442 |
The cookie will be returned automatically with subsequent responses |
| 443 |
made by the Browser instance whenever that's appropriate. |
| 444 |
|
| 445 |
cookie_string should be a valid value of the Set-Cookie header. |
| 446 |
|
| 447 |
For example: |
| 448 |
|
| 449 |
.. code-block:: python |
| 450 |
|
| 451 |
browser.set_cookie( |
| 452 |
"sid=abcdef; expires=Wednesday, 09-Nov-06 23:12:40 GMT") |
| 453 |
|
| 454 |
Currently, this method does not allow for adding RFC 2986 cookies. |
| 455 |
This limitation will be lifted if anybody requests it. |
| 456 |
|
| 457 |
See also :meth:`set_simple_cookie()` for an easier way to set cookies |
| 458 |
without needing to create a Set-Cookie header string. |
| 459 |
""" |
| 460 |
if self._response is None: |
| 461 |
raise BrowserStateError("not viewing any document") |
| 462 |
if self.request.get_type() not in ["http", "https"]: |
| 463 |
raise BrowserStateError("can't set cookie for non-HTTP/HTTPS " |
| 464 |
"transactions") |
| 465 |
cookiejar = self._ua_handlers["_cookies"].cookiejar |
| 466 |
response = self.response() |
| 467 |
headers = response.info() |
| 468 |
headers["Set-cookie"] = cookie_string |
| 469 |
cookiejar.extract_cookies(response, self.request) |
| 470 |
|
| 471 |
def set_simple_cookie(self, name, value, domain, path='/'): |
| 472 |
''' |
| 473 |
Similar to :meth:`set_cookie()` except that instead of using a |
| 474 |
cookie string, you simply specify the `name`, `value`, `domain` |
| 475 |
and optionally the `path`. |
| 476 |
The created cookie will never expire. For example: |
| 477 |
|
| 478 |
.. code-block:: python |
| 479 |
|
| 480 |
browser.set_simple_cookie('some_key', 'some_value', '.example.com', |
| 481 |
path='/some-page') |
| 482 |
''' |
| 483 |
self.cookiejar.set_cookie( |
| 484 |
Cookie(0, name, value, None, False, domain, True, False, path, |
| 485 |
True, False, None, False, None, None, None)) |
| 486 |
|
| 487 |
@property |
| 488 |
def cookiejar(self): |
| 489 |
' Return the current cookiejar (:class:`mechanize.CookieJar`) or None ' |
| 490 |
try: |
| 491 |
return self._ua_handlers["_cookies"].cookiejar |
| 492 |
except Exception: |
| 493 |
pass |
| 494 |
|
| 495 |
def set_header(self, header, value=None): |
| 496 |
''' |
| 497 |
Convenience method to set a header value in `self.addheaders` |
| 498 |
so that the header is sent out with all requests automatically. |
| 499 |
|
| 500 |
:param header: The header name, e.g. User-Agent |
| 501 |
:param value: The header value. If set to None the header is removed. |
| 502 |
''' |
| 503 |
found = False |
| 504 |
header = normalize_header_name(header) |
| 505 |
q = header.lower() |
| 506 |
remove = [] |
| 507 |
for i, (k, v) in enumerate(tuple(self.addheaders)): |
| 508 |
if k.lower() == q: |
| 509 |
if value: |
| 510 |
self.addheaders[i] = (header, value) |
| 511 |
found = True |
| 512 |
else: |
| 513 |
remove.append(i) |
| 514 |
if not found: |
| 515 |
self.addheaders.append((header, value)) |
| 516 |
if remove: |
| 517 |
for i in reversed(remove): |
| 518 |
del self.addheaders[i] |
| 519 |
|
| 520 |
def links(self, **kwds): |
| 521 |
"""Return iterable over links (:class:`mechanize.Link` objects).""" |
| 522 |
if not self.viewing_html(): |
| 523 |
raise BrowserStateError("not viewing HTML") |
| 524 |
links = self._factory.links() |
| 525 |
if kwds: |
| 526 |
return self._filter_links(links, **kwds) |
| 527 |
else: |
| 528 |
return links |
| 529 |
|
| 530 |
def forms(self): |
| 531 |
"""Return iterable over forms. |
| 532 |
|
| 533 |
The returned form objects implement the :class:`mechanize.HTMLForm` |
| 534 |
interface. |
| 535 |
|
| 536 |
""" |
| 537 |
if not self.viewing_html(): |
| 538 |
raise BrowserStateError("not viewing HTML") |
| 539 |
return self._factory.forms() |
| 540 |
|
| 541 |
def global_form(self): |
| 542 |
"""Return the global form object, or None if the factory implementation |
| 543 |
did not supply one. |
| 544 |
|
| 545 |
The "global" form object contains all controls that are not descendants |
| 546 |
of any FORM element. |
| 547 |
|
| 548 |
The returned form object implements the :class:`mechanize.HTMLForm` |
| 549 |
interface. |
| 550 |
|
| 551 |
This is a separate method since the global form is not regarded as part |
| 552 |
of the sequence of forms in the document -- mostly for |
| 553 |
backwards-compatibility. |
| 554 |
|
| 555 |
""" |
| 556 |
if not self.viewing_html(): |
| 557 |
raise BrowserStateError("not viewing HTML") |
| 558 |
return self._factory.global_form |
| 559 |
|
| 560 |
def viewing_html(self): |
| 561 |
"""Return whether the current response contains HTML data.""" |
| 562 |
if self._response is None: |
| 563 |
raise BrowserStateError("not viewing any document") |
| 564 |
return self._factory.is_html |
| 565 |
|
| 566 |
def encoding(self): |
| 567 |
if self._response is None: |
| 568 |
raise BrowserStateError("not viewing any document") |
| 569 |
return self._factory.encoding |
| 570 |
|
| 571 |
def title(self): |
| 572 |
' Return title, or None if there is no title element in the document. ' |
| 573 |
if not self.viewing_html(): |
| 574 |
raise BrowserStateError("not viewing HTML") |
| 575 |
return self._factory.title |
| 576 |
|
| 577 |
def select_form(self, name=None, predicate=None, nr=None, **attrs): |
| 578 |
"""Select an HTML form for input. |
| 579 |
|
| 580 |
This is a bit like giving a form the "input focus" in a browser. |
| 581 |
|
| 582 |
If a form is selected, the Browser object supports the HTMLForm |
| 583 |
interface, so you can call methods like :meth:`set_value()`, |
| 584 |
:meth:`set()`, and :meth:`click()`. |
| 585 |
|
| 586 |
Another way to select a form is to assign to the .form attribute. The |
| 587 |
form assigned should be one of the objects returned by the |
| 588 |
:meth:`forms()` method. |
| 589 |
|
| 590 |
If no matching form is found, |
| 591 |
:class:`mechanize.FormNotFoundError` is raised. |
| 592 |
|
| 593 |
If `name` is specified, then the form must have the indicated name. |
| 594 |
|
| 595 |
If `predicate` is specified, then the form must match that function. |
| 596 |
The predicate function is passed the :class:`mechanize.HTMLForm` as its |
| 597 |
single argument, and should return a boolean value indicating whether |
| 598 |
the form matched. |
| 599 |
|
| 600 |
`nr`, if supplied, is the sequence number of the form (where 0 is the |
| 601 |
first). Note that control 0 is the first form matching all the other |
| 602 |
arguments (if supplied); it is not necessarily the first control in the |
| 603 |
form. The "global form" (consisting of all form controls not contained |
| 604 |
in any FORM element) is considered not to be part of this sequence and |
| 605 |
to have no name, so will not be matched unless both name and nr are |
| 606 |
None. |
| 607 |
|
| 608 |
You can also match on any HTML attribute of the `<form>` tag by passing |
| 609 |
in the attribute name and value as keyword arguments. To convert HTML |
| 610 |
attributes into syntactically valid python keyword arguments, the |
| 611 |
following simple rule is used. The python keyword argument name is |
| 612 |
converted to an HTML attribute name by: Replacing all underscores with |
| 613 |
hyphens and removing any trailing underscores. You can pass in strings, |
| 614 |
functions or regular expression objects as the values to match. For |
| 615 |
example: |
| 616 |
|
| 617 |
.. code-block:: python |
| 618 |
|
| 619 |
# Match form with the exact action specified |
| 620 |
br.select_form(action='http://foo.com/submit.php') |
| 621 |
# Match form with a class attribute that contains 'login' |
| 622 |
br.select_form(class_=lambda x: 'login' in x) |
| 623 |
# Match form with a data-form-type attribute that matches a regex |
| 624 |
br.select_form(data_form_type=re.compile(r'a|b')) |
| 625 |
|
| 626 |
""" |
| 627 |
if not self.viewing_html(): |
| 628 |
raise BrowserStateError("not viewing HTML") |
| 629 |
if name is None and predicate is None and nr is None and not attrs: |
| 630 |
raise ValueError( |
| 631 |
"at least one argument must be supplied to specify form") |
| 632 |
|
| 633 |
global_form = self._factory.global_form |
| 634 |
if nr is None and name is None and predicate is not None and predicate( |
| 635 |
global_form): |
| 636 |
self.form = global_form |
| 637 |
return |
| 638 |
|
| 639 |
def attr_selector(q): |
| 640 |
if is_string(q): |
| 641 |
return lambda x: x == q |
| 642 |
if callable(q): |
| 643 |
return q |
| 644 |
return lambda x: q.match(x) is not None |
| 645 |
attrsq = {aname.rstrip('_').replace('_', '-'): attr_selector(v) |
| 646 |
for aname, v in iteritems(attrs)} |
| 647 |
|
| 648 |
def form_attrs_match(form_attrs): |
| 649 |
for aname, q in iteritems(attrsq): |
| 650 |
val = form_attrs.get(aname) |
| 651 |
if val is None or not q(val): |
| 652 |
return False |
| 653 |
return True |
| 654 |
|
| 655 |
orig_nr = nr |
| 656 |
for form in self.forms(): |
| 657 |
if name is not None and name != form.name: |
| 658 |
continue |
| 659 |
if predicate is not None and not predicate(form): |
| 660 |
continue |
| 661 |
if nr: |
| 662 |
nr -= 1 |
| 663 |
continue |
| 664 |
if attrs and not form_attrs_match(form.attrs): |
| 665 |
continue |
| 666 |
self.form = form |
| 667 |
break |
| 668 |
else: |
| 669 |
|
| 670 |
description = [] |
| 671 |
if name is not None: |
| 672 |
description.append("name '%s'" % name) |
| 673 |
if predicate is not None: |
| 674 |
description.append("predicate %s" % predicate) |
| 675 |
if orig_nr is not None: |
| 676 |
description.append("nr %d" % orig_nr) |
| 677 |
if attrs: |
| 678 |
for k, v in iteritems(attrs): |
| 679 |
description.append('%s = %r' % (k, v)) |
| 680 |
description = ", ".join(description) |
| 681 |
raise FormNotFoundError("no form matching " + description) |
| 682 |
|
| 683 |
def click(self, *args, **kwds): |
| 684 |
"""See :meth:`mechanize.HTMLForm.click()` for documentation.""" |
| 685 |
if not self.viewing_html(): |
| 686 |
raise BrowserStateError("not viewing HTML") |
| 687 |
request = self.form.click(*args, **kwds) |
| 688 |
return self._add_referer_header(request) |
| 689 |
|
| 690 |
def submit(self, *args, **kwds): |
| 691 |
"""Submit current form. |
| 692 |
|
| 693 |
Arguments are as for :meth:`mechanize.HTMLForm.click()`. |
| 694 |
|
| 695 |
Return value is same as for :meth:`open()`. |
| 696 |
""" |
| 697 |
return self.open(self.click(*args, **kwds)) |
| 698 |
|
| 699 |
def click_link(self, link=None, **kwds): |
| 700 |
"""Find a link and return a Request object for it. |
| 701 |
|
| 702 |
Arguments are as for :meth:`find_link()`, except that a link may be |
| 703 |
supplied as the first argument. |
| 704 |
|
| 705 |
""" |
| 706 |
if not self.viewing_html(): |
| 707 |
raise BrowserStateError("not viewing HTML") |
| 708 |
if not link: |
| 709 |
link = self.find_link(**kwds) |
| 710 |
else: |
| 711 |
if kwds: |
| 712 |
raise ValueError( |
| 713 |
"either pass a Link, or keyword arguments, not both") |
| 714 |
request = self.request_class(link.absolute_url) |
| 715 |
return self._add_referer_header(request) |
| 716 |
|
| 717 |
def follow_link(self, link=None, **kwds): |
| 718 |
"""Find a link and :meth:`open()` it. |
| 719 |
|
| 720 |
Arguments are as for :meth:`click_link()`. |
| 721 |
|
| 722 |
Return value is same as for :meth:`open()`. |
| 723 |
|
| 724 |
""" |
| 725 |
return self.open(self.click_link(link, **kwds)) |
| 726 |
|
| 727 |
def find_link(self, |
| 728 |
text=None, |
| 729 |
text_regex=None, |
| 730 |
name=None, |
| 731 |
name_regex=None, |
| 732 |
url=None, |
| 733 |
url_regex=None, |
| 734 |
tag=None, |
| 735 |
predicate=None, |
| 736 |
nr=0): |
| 737 |
"""Find a link in current page. |
| 738 |
|
| 739 |
Links are returned as :class:`mechanize.Link` objects. Examples: |
| 740 |
|
| 741 |
.. code-block:: python |
| 742 |
|
| 743 |
# Return third link that .search()-matches the regexp "python" (by |
| 744 |
# ".search()-matches", I mean that the regular expression method |
| 745 |
# .search() is used, rather than .match()). |
| 746 |
find_link(text_regex=re.compile("python"), nr=2) |
| 747 |
|
| 748 |
# Return first http link in the current page that points to |
| 749 |
# somewhere on python.org whose link text (after tags have been |
| 750 |
# removed) is exactly "monty python". |
| 751 |
find_link(text="monty python", |
| 752 |
url_regex=re.compile("http.*python.org")) |
| 753 |
|
| 754 |
# Return first link with exactly three HTML attributes. |
| 755 |
find_link(predicate=lambda link: len(link.attrs) == 3) |
| 756 |
|
| 757 |
Links include anchors `<a>`, image maps `<area>`, and frames |
| 758 |
`<iframe>`. |
| 759 |
|
| 760 |
All arguments must be passed by keyword, not position. Zero or more |
| 761 |
arguments may be supplied. In order to find a link, all arguments |
| 762 |
supplied must match. |
| 763 |
|
| 764 |
If a matching link is not found, :class:`mechanize.LinkNotFoundError` |
| 765 |
is raised. |
| 766 |
|
| 767 |
:param text: link text between link tags: e.g. <a href="blah">this |
| 768 |
bit</a> with whitespace compressed. |
| 769 |
:param text_regex: link text between tag (as defined above) must match |
| 770 |
the regular expression object or regular expression string passed |
| 771 |
as this argument, if supplied |
| 772 |
:param name: as for text and text_regex, but matched |
| 773 |
against the name HTML attribute of the link tag |
| 774 |
:param url: as for text and text_regex, but matched against the |
| 775 |
URL of the link tag (note this matches against Link.url, which is a |
| 776 |
relative or absolute URL according to how it was written in the |
| 777 |
HTML) |
| 778 |
:param tag: element name of opening tag, e.g. "a" |
| 779 |
:param predicate: a function taking a Link object as its single |
| 780 |
argument, returning a boolean result, indicating whether the links |
| 781 |
:param nr: matches the nth link that matches all other |
| 782 |
criteria (default 0) |
| 783 |
|
| 784 |
""" |
| 785 |
try: |
| 786 |
return next(self._filter_links( |
| 787 |
self._factory.links(), text, text_regex, name, name_regex, url, |
| 788 |
url_regex, tag, predicate, nr)) |
| 789 |
except StopIteration: |
| 790 |
raise LinkNotFoundError() |
| 791 |
|
| 792 |
def __getattr__(self, name): |
| 793 |
|
| 794 |
form = self.__dict__.get("form") |
| 795 |
if form is None: |
| 796 |
raise AttributeError( |
| 797 |
"%s instance has no attribute %s (perhaps you forgot to " |
| 798 |
".select_form()?)" % (self.__class__, name)) |
| 799 |
return getattr(form, name) |
| 800 |
|
| 801 |
def __getitem__(self, name): |
| 802 |
if self.form is None: |
| 803 |
raise BrowserStateError('No form selected') |
| 804 |
return self.form[name] |
| 805 |
|
| 806 |
def __setitem__(self, name, val): |
| 807 |
if self.form is None: |
| 808 |
raise BrowserStateError('No form selected') |
| 809 |
self.form[name] = val |
| 810 |
|
| 811 |
def _filter_links(self, |
| 812 |
links, |
| 813 |
text=None, |
| 814 |
text_regex=None, |
| 815 |
name=None, |
| 816 |
name_regex=None, |
| 817 |
url=None, |
| 818 |
url_regex=None, |
| 819 |
tag=None, |
| 820 |
predicate=None, |
| 821 |
nr=0): |
| 822 |
if not self.viewing_html(): |
| 823 |
raise BrowserStateError("not viewing HTML") |
| 824 |
|
| 825 |
orig_nr = nr |
| 826 |
|
| 827 |
for link in links: |
| 828 |
if url is not None and url != link.url: |
| 829 |
continue |
| 830 |
if url_regex is not None and not re.search(url_regex, link.url): |
| 831 |
continue |
| 832 |
if (text is not None and (link.text is None or text != link.text)): |
| 833 |
continue |
| 834 |
if ( |
| 835 |
text_regex is not None and ( |
| 836 |
link.text is None or not re.search( |
| 837 |
text_regex, link.text))): |
| 838 |
continue |
| 839 |
if name is not None and name != dict(link.attrs).get("name"): |
| 840 |
continue |
| 841 |
if name_regex is not None: |
| 842 |
link_name = dict(link.attrs).get("name") |
| 843 |
if link_name is None or not re.search(name_regex, link_name): |
| 844 |
continue |
| 845 |
if tag is not None and tag != link.tag: |
| 846 |
continue |
| 847 |
if predicate is not None and not predicate(link): |
| 848 |
continue |
| 849 |
if nr: |
| 850 |
nr -= 1 |
| 851 |
continue |
| 852 |
yield link |
| 853 |
nr = orig_nr |