MECHANIZE(1)

πŸ“¦ version 0.4.7, in ubuntu jammy

✨ MECHANIZE(1) ✨

okay so bestie, welcome to the mechanize manual page β€” section 1 of the manual, iykyk πŸ’…. this is the whole entire documentation and it's A Lot, so grab a strawberry drink πŸ“ and let's go.

NAME

mechanize β€” mechanize Documentation

Stateful programmatic web browsing in Python. Browse pages programmatically with easy HTML form filling and clicking of links. yes literally that's the whole vibe: your code gets a browser and the browser does the clicking 🫢


FREQUENTLY ASKED QUESTIONS

Contents

  • General
    • Which version of Python do I need?
    • What dependencies does mechanize need?
    • What license does mechanize use?
  • Usage
    • I'm not getting the HTML page I expected to see?
    • Is JavaScript supported?
    • My HTTP response data is truncated?
    • Is there any example code?
  • Cookies
    • Which HTTP cookie protocols does mechanize support?
    • What about RFC 2109?
    • Why don't I have any cookies?
    • My response claims to be empty, but I know it's not?
    • What's the difference between the .load() and .revert() methods of CookieJar?
    • Is it threadsafe?
    • How do I do X?
  • Forms
    • How do I figure out what control names and values to use?
    • What do those '*' characters mean in the string representations of list controls?
    • What do those parentheses (round brackets) mean in the string representations of list controls?
    • Why doesn't <some control> turn up in the data returned by .click*() when that control has non-None value?
    • Why does mechanize not follow the HTML 4.0 / RFC 1866 standards for RADIO and multiple-selection SELECT controls?
    • Why does .click() ing on a button not work for me?
    • How do I change INPUT TYPE=HIDDEN field values (for example, to emulate the effect of JavaScript code)?
    • I'm having trouble debugging my code.
    • I have a control containing a list of integers. How do I select the one whose value is nearest to the one I want?
  • Miscellaneous
    • I want to see what my web browser is doing?
    • JavaScript is messing up my web-scraping. What do I do?

General

Which version of Python do I need?

mechanize works on all python versions, python 2 (>= 2.7) and 3 (>= 3.5). all of them bestie, it's giving equal opportunity πŸ‘‘

What dependencies does mechanize need?

html5lib

that's it. that's the whole list. one (1) dependency, iconic ✨

What license does mechanize use?

mechanize is licensed under the BSD-3-clause license. open source queen πŸ’–


Usage

I'm not getting the HTML page I expected to see?

See debugging. 😭 been there

Is JavaScript supported?

No, sorry. 🫠 See JavaScript is messing up my web-scraping. What do I do?

My HTTP response data is truncated?

mechanize.Browser's response objects support the .seek() method, and can still be used after .close() has been called. Response data is not fetched until it is needed, so navigating away from a URL before fetching all of the response will truncate it πŸ’€. Call response.get_data() before navigation if you don't want that to happen. protect your data bestie, it's giving fetch-on-demand.

Is there any example code?

Look in the examples/ directory. Note that the examples on the forms page are executable as-is. Contributions of example code would be very welcome! πŸŽ€


Cookies

Netscape and RFC 2965. RFC 2965 handling is switched off by default.

What about RFC 2109?

RFC 2109 cookies are currently parsed as Netscape cookies, and treated by default as RFC 2965 cookies thereafter if RFC 2965 handling is enabled, or as Netscape cookies otherwise. it's giving identity crisis ngl πŸ™ˆ

Why don't I have any cookies?

See cookies. πŸͺ

My response claims to be empty, but I know it's not?

Did you call response.read() (e.g., in a debug statement), then forget that all the data has already been read? 😭 In that case, you may want to use mechanize.response_seek_wrapper. mechanize.Browser always returns seekable responses, so it's not necessary to use this explicitly in that case.

What's the difference between the .load() and .revert() methods of CookieJar?

.load() appends cookies from a file. .revert() discards all existing cookies held by the CookieJar first (but it won't lose any existing cookies if the loading fails). so like, revert() clears the runway but only if the new thing actually lands. safety queen πŸ’…

Is it threadsafe?

See threading.

How do I do X?

Refer to the API documentation in browser_api.


Forms

How do I figure out what control names and values to use?

print(form) is usually all you need. ✨ In your code, things like the HTMLForm.items attribute of mechanize.HTMLForm instances can be useful to inspect forms at runtime. Note that it's possible to use item labels instead of item names, which can be useful β€” use the by_label arguments to the various methods, and the .get_value_by_label() / .set_value_by_label() methods on ListControl.

What do those '*' characters mean in the string representations of list controls?

A * next to an item means that item is selected. ⭐

What do those parentheses (round brackets) mean in the string representations of list controls?

Parentheses (foo) around an item mean that item is disabled. 🚫

Why doesn't <some control> turn up in the data returned by .click*() when that control has non-None value?

Either the control is disabled, or it is not successful for some other reason. 'Successful' (see HTML 4 specification) means that the control will cause data to get sent to the server. if it's not successful, it's not showing up, periodt.

Why does mechanize not follow the HTML 4.0 / RFC 1866 standards for RADIO and multiple-selection SELECT controls?

Because by default, it follows browser behaviour when setting the initially-selected items in list controls that have no items explicitly selected in the HTML. matching the vibes of real browsers, not the spec πŸ¦‹

Why does .click() ing on a button not work for me?

Clicking on a RESET button doesn't do anything, by design β€” this is a library for web automation, not an interactive browser. Even in an interactive browser, clicking on RESET sends nothing to the server, so there is little point in having .click() do anything special here.

Clicking on a BUTTON TYPE=BUTTON doesn't do anything either, also by design. This time, the reason is that that BUTTON is only in the HTML standard so that one can attach JavaScript callbacks to its events. Their execution may result in information getting sent back to the server. mechanize, however, knows nothing about these callbacks, so it can't do anything useful with a click on a BUTTON whose type is BUTTON.

Generally, JavaScript may be messing things up in all kinds of ways. See JavaScript is messing up my web-scraping. What do I do?.

How do I change INPUT TYPE=HIDDEN field values (for example, to emulate the effect of JavaScript code)?

As with any control, set the control's readonly attribute false.

form.find_control("foo").readonly = False # allow changing .value of control foo
form.set_all_readonly(False) # allow changing the .value of all controls

I'm having trouble debugging my code.

See debugging.

I have a control containing a list of integers. How do I select the one whose value is nearest to the one I want?

import bisect
def closest_int_value(form, ctrl_name, value):
    values = map(int, [item.name for item in form.find_control(ctrl_name).items])
    return str(values[bisect.bisect(values, value) - 1])

form["distance"] = [closest_int_value(form, "distance", 23)]

Miscellaneous

I want to see what my web browser is doing?

Use the developer tools for your browser (you may have to install them first). These provide excellent views into all HTTP requests/responses in the browser. πŸ”

JavaScript is messing up my web-scraping. What do I do?

JavaScript is used in web pages for many purposes β€” for example: creating content that was not present in the page at load time, submitting or filling in parts of forms in response to user actions, setting cookies, etc. mechanize does not provide any support for JavaScript.

If you come across this in a page you want to automate, you have a few options. Here they are, roughly in order of simplicity:

  • Figure out what the JavaScript is doing and emulate it in your Python code. The simplest case is if the JavaScript is setting some cookies. In that case you can inspect the cookies in your browser and emulate setting them in mechanize with mechanize.Browser.set_simple_cookie().
  • More complex is to use your browser developer tools to see exactly what requests are sent by the browser and emulate them in mechanize by using mechanize.Request to create the request manually and open it with mechanize.Browser.open().
  • Third is to use some browser automation framework/library to scrape the site instead of using mechanize. These libraries typically drive a headless version of a full browser that can execute all JavaScript. They are typically much slower than using mechanize and far more resource intensive, but do work as a last resort.

BROWSER API

API documentation for the mechanize Browser object. You can create a mechanize Browser instance as:

from mechanize import Browser
br = Browser()

Contents

  • Browser API
    • The Browser
    • The Request
    • The Response
    • Miscellaneous

The Browser

class mechanize.Browser(history=None, request_class=None, content_parser=None, factory_class=<class 'mechanize._html.Factory'>, allow_xhtml=False)

Browser-like class with support for history, forms and links. 🌸

BrowserStateError is raised whenever the browser is in the wrong state to complete the requested operation β€” e.g., when back() is called when the browser history is empty, or when follow_link() is called when the current response does not contain HTML data.

Public attributes:

  • request: current request (mechanize.Request)
  • form: currently selected form (see select_form())

Parameters

  • history β€” object implementing the mechanize.History interface. Note this interface is still experimental and may change in future. This object is owned by the browser instance and must not be shared among browsers.
  • request_class β€” Request class to use. Defaults to mechanize.Request
  • content_parser β€” A function that is responsible for parsing received html/xhtml content. See the builtin mechanize._html.content_parser() function for details on the interface this function must support.
  • factory_class β€” HTML Factory class to use. Defaults to mechanize.Factory

add_client_certificate(url, key_file, cert_file)

Add an SSL client certificate, for HTTPS client auth. πŸ”

key_file and cert_file must be filenames of the key and certificate files, in PEM format. You can use e.g. OpenSSL to convert a p12 (PKCS 12) file to PEM format:


(part 1 of 10 bestie, we're not even close to done πŸ’…)

...so if you're building that .pem yourself, it goes a lil something like this:

openssl pkcs12 -clcerts -nokeys -in cert.p12 -out cert.pem
openssl pkcs12 -nocerts -in cert.p12 -out key.pem
heads up bestie 🚨 client certificate password input is very inflexible ATM. Right now this seems to be console only, which is presumably the default behaviour of libopenssl. In future mechanize may support third-party libraries that (I assume) allow more options here. So like… it is what it is for now πŸ™ˆ

back(n=1)

Go back n steps in history, and return response object. Time travel but make it HTML βͺ✨

  • n β€” go back this number of steps (default 1 step)

click(*args, **kwds)

See mechanize.HTMLForm.click() for documentation. That's it, that's the whole vibe β€” the docs live over there, go look πŸ‘€

Find a link and return a Request object for it.

Arguments are as for find_link(), except that a link may be supplied as the first argument. Slight upgrade, same energy πŸ’…

property cookiejar

Return the current cookiejar (mechanize.CookieJar) or None. πŸͺ Either you got cookies or you got nothing, no in-between.

Find a link in current page. πŸ”

Links are returned as mechanize.Link objects. Examples, and yes they're iconic:

# Return third link that .search()-matches the regexp "python" (by
# ".search()-matches", I mean that the regular expression method
# .search() is used, rather than .match()).
find_link(text_regex=re.compile("python"), nr=2)

# Return first http link in the current page that points to
# somewhere on python.org whose link text (after tags have been
# removed) is exactly "monty python".
find_link(text="monty python",
        url_regex=re.compile("http.*python.org"))

# Return first link with exactly three HTML attributes.
find_link(predicate=lambda link: len(link.attrs) == 3)

Links include anchors <a>, image maps <area>, and frames <iframe>. All of them. The whole link-adjacent family 🫢

All arguments must be passed by keyword, not position. Zero or more arguments may be supplied. In order to find a link, all arguments supplied must match. No partial credit, bestie β€” it's all or nothing.

If a matching link is not found, mechanize.LinkNotFoundError is raised. 😭

Parameters

  • text β€” link text between link tags: e.g. <a href="blah">this bit</a> with whitespace compressed.
  • text_regex β€” link text between tag (as defined above) must match the regular expression object or regular expression string passed as this argument, if supplied
  • name β€” as for text and text_regex, but matched against the name HTML attribute of the link tag
  • url β€” as for text and text_regex, but matched against the URL of the link tag (note this matches against Link.url, which is a relative or absolute URL according to how it was written in the HTML)
  • tag β€” element name of opening tag, e.g. "a"
  • predicate β€” a function taking a Link object as its single argument, returning a boolean result, indicating whether the links
  • nr β€” matches the *n*th link that matches all other criteria (default 0)

Find a link and open() it. Find + open = the two-step combo move πŸ’ƒ

Arguments are as for click_link().

Return value is same as for open().

forms()

Return iterable over forms.

The returned form objects implement the mechanize.HTMLForm interface.

geturl()

Get URL of current document. Where even are we rn πŸ“

global_form()

Return the global form object, or None if the factory implementation did not supply one.

The "global" form object contains all controls that are not descendants of any FORM element.

The returned form object implements the mechanize.HTMLForm interface.

This is a separate method since the global form is not regarded as part of the sequence of forms in the document β€” mostly for backwards-compatibility. It's giving legacy but we love her anyway πŸ’œ

Return iterable over links (mechanize.Link objects).

open(url_or_request, data=None, timeout=<object object>)

Open a URL. Loads the page so that you can subsequently use forms(), links(), etc. on it. This is the main character method fr fr πŸ‘‘

Parameters

  • url_or_request β€” Either a URL or a mechanize.Request
  • data (dict) β€” data to send with a POST request
  • timeout β€” Timeout in seconds

Returns A mechanize.Response object

open_novisit(url_or_request, data=None, timeout=<object object>)

Open a URL without visiting it.

Browser state (including request, response, history, forms and links) is left unchanged by calling this function. No trace, no history entry, we were never here 🀫

The interface is the same as for open().

This is useful for things like fetching images. πŸ–ΌοΈ

See also retrieve()

reload()

Reload current document, and return response object. The F5 fantasy πŸ”„

response()

Return a copy of the current response.

The returned object has the same interface as the object returned by open()

retrieve(fullurl, filename=None, reporthook=None, data=None, timeout=<object object>, open=<built-in function open>)

Returns (filename, headers).

For remote objects, the default filename will refer to a temporary file. Temporary files are removed when the OpenerDirector.close() method is called. 🧹

For file: URLs, at present the returned filename is None. This may change in future.

If the actual number of bytes read is less than indicated by the Content-Length header, raises ContentTooShortError (a URLError subclass). The exception's .result attribute contains the (filename, headers) that would have been returned. So the data's still there even when it goes wrong β€” cute of her honestly πŸŽ€

select_form(name=None, predicate=None, nr=None, **attrs)

Select an HTML form for input.

This is a bit like giving a form the "input focus" in a browser.

If a form is selected, the Browser object supports the HTMLForm interface, so you can call methods like set_value(), set(), and click().

Another way to select a form is to assign to the .form attribute. The form assigned should be one of the objects returned by the forms() method.

If no matching form is found, mechanize.FormNotFoundError is raised. πŸ’€

If name is specified, then the form must have the indicated name.

If predicate is specified, then the form must match that function. The predicate function is passed the mechanize.HTMLForm as its single argument, and should return a boolean value indicating whether the form matched.

nr, if supplied, is the sequence number of the form (where 0 is the first). Note that control 0 is the first form matching all the other arguments (if supplied); it is not necessarily the first control in the form. The "global form" (consisting of all form controls not contained in any FORM element) is considered not to be part of this sequence and to have no name, so will not be matched unless both name and nr are None. Sneaky little exception, ik 😌

You can also match on any HTML attribute of the <form> tag by passing in the attribute name and value as keyword arguments. To convert HTML attributes into syntactically valid python keyword arguments, the following simple rule is used. The python keyword argument name is converted to an HTML attribute name by: Replacing all underscores with hyphens and removing any trailing underscores. You can pass in strings, functions or regular expression objects as the values to match. For example:

# Match form with the exact action specified
br.select_form(action='http://foo.com/submit.php')
# Match form with a class attribute that contains 'login'
br.select_form(class_=lambda x: 'login' in x)
# Match form with a data-form-type attribute that matches a regex
br.select_form(data_form_type=re.compile(r'a|b'))

set_ca_data(cafile=None, capath=None, cadata=None, context=None)

Set the SSL Context used for connecting to SSL servers. πŸ”

This method accepts the same arguments as the ssl.SSLContext.load_verify_locations() method from the python standard library. You can also pass a pre-built context via the context keyword argument. Note that to use this feature, you must be using python >= 2.7.9. In addition you can directly pass in a pre-built ssl.SSLContext as the context argument.

set_client_cert_manager(cert_manager)

Set a mechanize.HTTPClientCertMgr, or None. All or nothing bestie πŸŽ€

Set a cookie. πŸͺ

Note that it is NOT necessary to call this method under ordinary circumstances: cookie handling is normally entirely automatic. The intended use case is rather to simulate the setting of a cookie by client script in a web page (e.g. JavaScript). In that case, use of this method is necessary because mechanize currently does not support JavaScript, VBScript, etc. So it's a manual-mode-only situation, iykyk πŸ’…

The cookie is added exactly like it had just rolled in with the current response, as a result of the current request. Which means β€” and this is the part bestie, don't skip it β€” if it wouldn't be appropriate to set that cookie based on the current request, no cookie gets set. Periodt.

That cookie then comes back automatically with later responses from the same Browser instance, whenever that's appropriate. It just knows. πŸ’…

cookie_string needs to be a valid value for the Set-Cookie header, ok?

For example:

browser.set_cookie(
    "sid=abcdef; expires=Wednesday, 09-Nov-06 23:12:40 GMT")

Lowkey important caveat: right now this method does not support adding RFC 2986 cookies. That limitation will be lifted if anybody requests it. (so like… ask, bestie? 😭)

Also go peep set_simple_cookie() if you want the easy way to set cookies without hand-building a whole Set-Cookie header string. So much less typing, so much more slay. ✨

  • set_cookiejar(cookiejar) β€” Set a mechanize.CookieJar, or None. πŸͺ
  • set_debug_http(handle) β€” Print HTTP headers to sys.stdout.
  • set_debug_redirects(handle) β€” Log info about HTTP redirects (refreshes included, she's thorough πŸ’).

Logging happens via the module logging. The logger name is "mechanize.http_redirects". If you actually wanna see debug output, like:

import sys, logging
logger = logging.getLogger("mechanize.http_redirects")
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.INFO)

Other logger names that are relevant to this module:

  • mechanize.http_responses
  • mechanize.cookies

To turn on everything:

import sys, logging
logger = logging.getLogger("mechanize")
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.INFO)
  • set_debug_responses(handle) β€” Log HTTP response bodies. πŸ“

See set_debug_redirects() for the deets on logging.

Response objects may be .seek()able if this is set (currently the returned responses are, but the raised HTTPError exception responses are not).

  • set_handle_equiv(handle, head_parser_class=None) β€” Set whether to treat HTML http-equiv headers like HTTP headers.

Response objects may be .seek()able if this is set (currently the returned responses are, but the raised HTTPError exception responses are not).

  • set_handle_gzip(handle) β€” Add a header telling the server we handle gzip content encoding. But heads up: if the server sends gzip'ed content, it gets handled automatically anyway, regardless of this setting. So it's giving ✨courtesy notice✨ more than anything.
  • set_handle_redirect(handle) β€” Set whether to handle HTTP 30x redirections.
  • set_handle_referer(handle) β€” Set whether to add a Referer header to each request.
  • set_handle_refresh(handle, max_time=None, honor_time=True) β€” Set whether to handle HTTP Refresh headers.
  • set_handle_robots(handle) β€” Set whether to observe rules from robots.txt. πŸ€–
  • set_handled_schemes(schemes) β€” Set the sequence of URL scheme (protocol) strings.

For example: ua.set_handled_schemes(["http", "ftp"])

If this fails (with ValueError) because you passed an unknown scheme, the set of handled schemes will not be changed. She's not gonna half-do it, it's all or nothing, queen behavior. πŸ‘‘

  • set_header(header, value=None) β€” Convenience method that sets a header value in self.addheaders so the header gets sent out with all requests automatically. So effortless.

Parameters

  • header -- The header name, e.g. User-Agent
  • value -- The header value. If set to None the header is removed.
  • set_html(html, url='http://example.com/') β€” Set the response to a dummy one with the given HTML, plus the URL if you gave one.

This lets you parse that HTML afterwards, especially to extract forms info. If no URL was given, the default is "example.com".

  • set_password_manager(password_manager) β€” Set a mechanize.HTTPPasswordMgrWithDefaultRealm, or None. πŸ”
  • set_proxies(proxies=None, proxy_bypass=None) β€” Configure proxy settings.

Parameters

  • proxies -- dictionary mapping URL scheme to proxy specification. None means use the default system-specific settings.
  • proxy_bypass -- function taking a hostname, returning whether the proxy should be used. None means use the default system-specific settings.

The default is to try to get proxy settings from the system (go read the docs for urllib.urlopen for info about the system-specific methods used -- and note that's urllib, not urllib2, bestie, don't get it twisted πŸ™ˆ).

To avoid all use of proxies, pass an empty proxies dict.

>>> ua = UserAgentBase()
>>> def proxy_bypass(hostname):
...     return hostname == "noproxy.com"
>>> ua.set_proxies(
...     {"http": "joe:password@myproxy.example.com:3128",
...      "ftp": "proxy.example.com"},
...     proxy_bypass)
  • set_proxy_password_manager(password_manager) β€” Set a mechanize.HTTPProxyPasswordMgr, or None.
  • set_request_gzip(handle) β€” Add a header telling the server we handle gzip content encoding. And again, same vibe as before: if the server sends gzip'ed content, it's handled automatically in any case, regardless of this setting. πŸ’«
  • set_response(response) β€” Replace the current response with (a copy of) response.

response may be None.

This is intended mostly for HTML-preprocessing.

  • set_simple_cookie(name, value, domain, path='/') β€” Similar to set_cookie() except instead of feeding it a cookie string, you just specify the name, value, domain and optionally the path. The created cookie will never expire. Forever girlie. For example:
browser.set_simple_cookie('some_key', 'some_value', '.example.com',
                          path='/some-page')
  • submit(*args, **kwds) β€” Submit the current form. πŸ“¬

Arguments are the same as for mechanize.HTMLForm.click().

Return value is the same as for open().

  • title() β€” Return the title, or None if there's no title element in the document.
  • viewing_html() β€” Return whether the current response contains HTML data.
  • visit_response(response, request=None) β€” Visit the response, as if it had been open() ed.

Unlike set_response(), this updates history instead of replacing the current response. Big difference, don't mix them up bestie. πŸ¦‹


πŸŽ€ The Request πŸŽ€

class mechanize.Request(url, data=None, headers={},
origin_req_host=None, unverifiable=False, visit=None, timeout=<object
object>, method=None)

A request for some network resource. And listen: if you set the method to 'GET' while the data is a dict, then it gets automatically appended to the URL. If you leave method as None, then the method auto-sets to POST and the data becomes part of the POST request. She picks for you, and she picks well. πŸ’…

Parameters

  • url (str) -- The URL to request
  • data -- Data to send with this request. Can be either a dictionary (which gets encoded and sent as application/x-www-form-urlencoded data) or a bytestring (which gets sent as is). If you use a bytestring you should also set the Content-Type header appropriately.
  • headers (dict) -- Headers to send with this request
  • method (str) -- Method to use for HTTP requests. If not specified, mechanize will choose GET or POST automatically as appropriate.
  • timeout (float) -- Timeout in seconds

The remaining arguments are for internal use. Not for you, bestie. πŸ™ˆ

  • add_data(data) β€” Set the data (a bytestring) to be sent with this request
  • add_header(key, val=None) β€” Add the specified header, replacing the existing one if needed. If val is None, remove the header.
  • add_unredirected_header(key, val) β€” Same as add_header() except this header will not be sent for redirected requests.
  • get_data() β€” The data to be sent with this request
  • get_header(header_name, default=None) β€” Get the value of the specified header. If it's absent, return default
  • get_method() β€” The method used for HTTP requests
  • has_data() β€” True iff there's some data to be sent with this request
  • has_header(header_name) β€” Check if the specified header is present
  • has_proxy() β€” Private method. πŸ‘€
  • header_items() β€” Get a copy of all headers for this request as a list of 2-tuples
  • set_data(data) β€” Set the data (a bytestring) to be sent with this request

🌈 The Response 🌈

Response objects in mechanize are seek()able file-like objects that support some extra methods, depending on the protocol used for the connection. The documentation below is for HTTP(s) responses, since those are the most common ones. (they're the main characters fr fr πŸ‘‘)

Additional methods present for HTTP responses:

class mechanize._mechanize.HTTPResponse
  • code β€” The HTTP status code
  • getcode() β€” Return HTTP status code
  • geturl() β€” Return the URL of the resource retrieved, commonly used to determine if a redirect was followed
  • get_all_header_names(normalize=True) β€” hands you a list of every header name. When normalize is True, the case of those names gets normalized. πŸ’–
  • get_all_header_values(name, normalize=True) β€” hands you a list of every value for the header name you asked for (and yes, that name is case-insensitive). Since HTTP headers can show up more than once, the return value is always a list, no exceptions. See rfc822.Message.getheaders(). ✨
  • info() β€” gives you the headers of the response as an rfc822.Message instance.
  • __getitem__(header_name) β€” returns the last HTTP Header matching the name you passed, as a string. mechanize Response objects lowkey act like dictionaries so you can grab header values conveniently. Like: response['Date']. You can access header values by header name, case-insensitively. But heads up bestie: when more than one header has the same name, only the value of the last one comes back β€” use get_all_header_values() if you want all of them. πŸ‘‘
  • get(header_name, default=None): β€” returns the header value for the header_name you specified, or default if that header isn't there. See __getitem__(). πŸ’…

🌈 Miscellaneous 🌈

class mechanize.Link(base_url, url, text, tag, attrs)

A link in a HTML document. πŸ”—

Variables:

  • absolute_url β€” the absolutized link URL
  • url β€” the link URL
  • base_url β€” the base URL that this link gets resolved against
  • text β€” the link text
  • tag β€” the link tag name
  • attrs β€” the tag attributes

class mechanize.History

So like, this will become public eventually, but the implied interface is not yet stable. 🚧 (we're being honest with you here, bestie)


mechanize._html.content_parser(data, url=None, response_info=None, transport_encoding=None, default_encoding='utf-8', is_html=True)

Parses data (a bytes object) into an etree representation, like xml.etree.ElementTree or lxml.etree. πŸ¦‹

Parameters:

  • data (bytes) β€” the data to parse
  • url β€” the URL of the document being parsed, or None
  • response_info β€” information about the document (contains all HTTP headers as HTTPMessage)
  • transport_encoding β€” the character encoding for the document being parsed, as specified in the HTTP headers, or None.
  • default_encoding β€” the character encoding to use if no encoding could be detected and no transport_encoding is specified
  • is_html β€” if the document is to be parsed as HTML.

πŸ“ HTML FORMS API πŸ“

Forms in HTML documents are represented by mechanize.HTMLForm. Every form is a collection of controls, and the different types of controls are represented by the various classes documented below. πŸŽ€


class mechanize.HTMLForm(action, method='GET', enctype='application/x-www-form-urlencoded', name=None, attrs=None, request_class=<class 'mechanize._request.Request'>, forms=None, labels=None, id_to_labels=None, encoding=None)

Bases: object

Represents a single HTML <form> ... </form> element. πŸ’–

A form is made up of a sequence of controls that usually have names, and those controls can take on various values. The values of the various types of controls represent, variously: text, zero-or-one-of-many or many-of-many choices, and files to be uploaded. Some controls can be clicked on to submit the form, and clickable controls' values sometimes include the coordinates of the click. πŸ–±οΈ

Forms can be filled in with data to be sent back to the server, and then submitted, using the click method to generate a request object suitable for passing to mechanize.urlopen() (or the click_request_data or click_pairs methods if you're integrating with third-party code). ✨

Usually, HTMLForm instances are not created directly. Instead, they get created automatically when you visit a page with a mechanize Browser. But if you do construct HTMLForm objects yourself, please note: an HTMLForm instance is only properly initialised after the fixup method has been called. See mechanize.ListControl for the reason this is required. πŸ‘€

Indexing a form (form["control_name"]) returns the named Control's value attribute. Assigning to a form index (form["control_name"] = something) is equivalent to assigning to the named Control's value attribute. If you need to be more specific than just supplying the control's name, use the set_value and get_value methods. πŸ’…

ListControl values are lists of item names β€” specifically, the names of the items that are selected and not disabled, and hence are "successful" (ie. cause data to be returned to the server). The list item's name is the value of the corresponding HTML element's"value" attribute.

Example:

<INPUT type="CHECKBOX" name="cheeses" value="leicester"></INPUT>
<INPUT type="CHECKBOX" name="cheeses" value="cheddar"></INPUT>

...defines a CHECKBOX control with name "cheeses" which has two items, named "leicester" and "cheddar". πŸ§€

Another example:

<SELECT name="more_cheeses">
  <OPTION>1</OPTION>
  <OPTION value="2" label="CHEDDAR">cheddar</OPTION>
</SELECT>

...defines a SELECT control with name "more_cheeses" which has two items, named "1" and "2" (because the OPTION element's value HTML attribute defaults to the element contents β€” see mechanize.SelectControl for more on these defaulting rules).

To select, deselect or otherwise manipulate individual list items, use the mechanize.HTMLForm.find_control() and mechanize.ListControl.get() methods. To set the whole value, do it like you would for any other control: use indexing or the set_value/get_value methods.

Example:

# select *only* the item named "cheddar"
form["cheeses"] = ["cheddar"]
# select "cheddar", leave other items unaffected
form.find_control("cheeses").get("cheddar").selected = True

Some controls (RADIO, and SELECT without the multiple attribute) can only have zero or one items selected at a time. Some controls (CHECKBOX, and SELECT with the multiple attribute) can have multiple items selected at a time. To set the whole value of a ListControl, assign a sequence to a form index:

form["cheeses"] = ["cheddar", "leicester"]

If the ListControl is not multiple-selection, the list you assign must be of length one. ⚠️

To check if a control has an item, if an item is selected, or if an item is successful (selected and not disabled), respectively:

"cheddar" in [item.name for item in form.find_control("cheeses").items]
"cheddar" in [item.name for item in form.find_control("cheeses").items
                and item.selected]
"cheddar" in form["cheeses"]
# or
"cheddar" in form.get_value("cheeses")

Note that some list items may be disabled (see below). πŸ™ˆ

Note the following mistake:

form[control_name] = control_value
assert form[control_name] == control_value  # not necessarily true

The reason for this is that form[control_name] always gives the list items in the order they were listed in the HTML.

List items (hence list values too) can be referred to in terms of list item labels rather than list item names, using the appropriate label arguments. Note that each item may have several labels. 🏷️

The question of default values of OPTION contents, labels and values is somewhat complicated: see mechanize.SelectControl and mechanize.ListControl.get_item_attrs() if you think you need to know.

Controls can be disabled or readonly. In either case, the control's value cannot be changed until you clear those flags (see example below). Disabled is the state typically represented by browsers by 'greying out' a control. Disabled controls are not 'successful' β€” they don't cause data to get returned to the server. Readonly controls usually appear in browsers as read-only text boxes. Readonly controls are successful. List items can also be disabled. Attempts to select or deselect disabled items fail with AttributeError. πŸ’€

If a lot of controls are readonly, it can be useful to do this:

form.set_all_readonly(False)

To clear a control's value attribute, so that it is not successful (until a value is subsequently set):

form.clear("cheeses")

More examples:

control = form.find_control("cheeses")
control.disabled = False
control.readonly = False
control.get("gruyere").disabled = True
control.items[0].selected = True

See the various Control classes for further documentation. Many methods take name, type, kind, id, label and nr arguments to specify which control to operate on: see mechanize.HTMLForm.find_control(). πŸ”

ControlNotFoundError (a subclass of ValueError) is raised if the specified control can't be found. This includes occasions where a non-ListControl is found, but the method (set, for example) requires a ListControl. ItemNotFoundError (a subclass of ValueError) is raised if a list item can't be found. ItemCountError (a subclass of ValueError) is raised if an attempt is made to select more than one item and the control doesn't allow that, or set/get_single are called and the control contains more than one item. AttributeError is raised if a control or item is readonly or disabled and an attempt is made to alter its value. 😭

Security note: Remember that any passwords you store in HTMLForm instances will be saved to disk in the clear if you pickle them (directly or indirectly). The simplest solution to this is to avoid pickling HTMLForm objects. You could also pickle before filling in any password, or just set the password to "" before pickling. πŸ”

Public attributes:

Variables

  • action β€” the full, absolute-URI version of the form's action πŸ’«
  • method β€” literally just "GET" or "POST", no in-between bestie
  • enctype β€” the MIME type the form uses for transfer encoding
  • name β€” the form's name (None if nobody gave it one, sad for it honestly)
  • attrs β€” a dictionary mapping the original HTML form attributes to their values
  • controls β€” a list of Control instances. Do NOT mess with this list directly β€” instead call form.new_control to make a Control and add it to the form, or control.add_to_form if you've already got a Control instance in hand 🫢

✨ Methods for form filling ✨

okay so most of these take basically the same arguments, which is a whole vibe. If you want the tea on the name, type, kind, label and nr args, go read mechanize.HTMLForm.find_control() πŸ’…



                 def find_control(self,
                                 name=None, type=None, kind=None, id=None,
                                 predicate=None, nr=None, label=None)

                 get_value(name=None, type=None, kind=None, id=None, nr=None,
                         by_label=False,  # by_label is deprecated
                         label=None)
                 set_value(value,
                         name=None, type=None, kind=None, id=None, nr=None,
                         by_label=False,  # by_label is deprecated
                         label=None)

                 clear_all()
                 clear(name=None, type=None, kind=None, id=None, nr=None, label=None)

                 set_all_readonly(readonly)

              Method applying only to FileControls:

                 add_file(file_object,
                      content_type="application/octet-stream", filename=None,
                      name=None, id=None, nr=None, label=None)

              Methods applying only to clickable controls:

                 click(name=None, type=None, id=None, nr=0, coord=(1,1), label=None)
                 click_request_data(name=None, type=None, id=None, nr=0, coord=(1,1),
                                 label=None)
                 click_pairs(name=None, type=None, id=None, nr=0, coord=(1,1),
                                 label=None)
heads up: that by_label kwarg? deprecated. it's giving legacy code, bestie πŸ™ˆ

add_file(file_object, content_type=None, filename=None, name=None, id=None, nr=None, label=None)

Adds a file to be uploaded πŸ“Ž β€” yes, the actual file-upload arc, we love to see it.

Parameters:

  • file_object β€” a file-like object (with a read method) that we read the upload data from
  • content_type β€” the MIME content type of the data we're uploading
  • filename β€” the filename to pass to the server

If filename is None, then no filename is sent to the server at all. ghost mode πŸ‘»

If content_type is None, the content type gets guessed based on the filename and the data read from the file object.

ngl, at the moment, the guessed content type is always application/octet-stream. every single time. no cap. 🫠

Also, note these genuinely useful HTML attributes of file upload controls (peep HTML 4.01 spec, section 17 for the receipts):

  • accept: a comma-separated list of content types that the server will handle correctly; you can use this to filter out non-conforming files ✨
  • size: XXX IIRC, this is indicative of whether the form wants multiple or single files
  • maxlength: XXX hint of max content length in bytes?

clear(name=None, type=None, kind=None, id=None, nr=None, label=None)

Clears the value attribute of a control 🧹

As a result, the affected control will not be successful until a value is subsequently set. And AttributeError gets raised on readonly controls β€” they said no takebacks and they meant it πŸ’€


clear_all()

Clears the value attributes of all the controls in the form. every last one. total reset energy πŸŽ€

See mechanize.HTMLForm.clear() for the details.


click(name=None, type=None, id=None, nr=0, coord=(1, 1), request_class=<class 'mechanize._request.Request'>, label=None)

Returns the request that would result from clicking on a control πŸ‘†βœ¨

The request object is a mechanize.Request instance, which you can hand straight to mechanize.urlopen. slay.

Only some control types can be clicked: INPUT/SUBMIT & BUTTON/SUBMIT buttons and IMAGEs. that's the clickable squad, periodt.

It'll click on the first clickable control, subject to the name, type and nr arguments (same rules as find_control). And if no name, type, id or number is specified and there are literally no clickable controls, a request gets returned for the form in its current, un-clicked, state. main character just standing there πŸ§β€β™€οΈ

IndexError is raised if any of name, type, id or nr is specified but no matching control is found. ValueError is raised if the HTMLForm has an enctype attribute that is not recognised. know the difference bestie, they are not the same

You can optionally specify a coordinate to click at, which only makes a difference if you clicked on an image πŸ–ΌοΈ (yes, pixel-hunting, iconic behaviour).


click_pairs(name=None, type=None, id=None, nr=0, coord=(1, 1), label=None)

Same energy as click_request_data, except it returns a list of (key, value) pairs πŸ’«

You can use this list as an argument to urllib.urlencode. This is usually only useful if you're using httplib or urllib rather than mechanize. It may also be useful if you want to manually tweak the keys and/or values β€” but honestly that shouldn't be necessary. Otherwise? just use the click method. fr fr.

note that this method is only useful for forms of MIME type x-www-form-urlencoded. In particular, it does not return the information required for file upload. If you need file upload and you're not using mechanize, use click_request_data. don't say I didn't warn you 😭

click_request_data(name=None, type=None, id=None, nr=0, coord=(1, 1), request_class=<class 'mechanize._request.Request'>, label=None)

Same as the click method, but it returns a tuple (url, data, headers) 🎁

You can use this data to send a request to the server. This is useful if you're using httplib or urllib rather than mechanize. Otherwise, use the click method. that's the whole thing 🫢


find_control(name=None, type=None, kind=None, id=None, predicate=None, nr=None, label=None)

Locates and returns some specific control within the form πŸ” the little detective moment.

At least one of the name, type, kind, predicate and nr arguments must be supplied. If no matching control is found, ControlNotFoundError is raised. so rude but okay

If name is specified, then the control must have the indicated name.

If type is specified then the control must have the specified type. In addition to the types possible for <input> HTML tags β€” "text", "password", "hidden", "submit", "image", "button", "radio", "checkbox", "file" β€” we also have "reset", "buttonbutton", "submitbutton", "resetbutton", "textarea", "select". yes, buttonbutton. I don't make the rules. πŸ’…

If kind is specified, then the control must fall into the specified group, each of which satisfies a particular interface. The kinds are "text", "list", "multilist", "singlelist", "clickable" and "file".

If id is specified, then the control must have the indicated id.

If predicate is specified, then the control must match that function. The predicate function is passed the control as its single argument, and should return a boolean value indicating whether the control matched. (a little yes/no vibe check ⭐)

nr, if supplied, is the sequence number of the control (where 0 is the first). Note that control 0 is the first control matching all the other arguments (if supplied) β€” it is not necessarily the first control in the form. Sneaky. And if no nr is supplied, AmbiguityError is raised if multiple controls match the other arguments. can't pick a favourite? then you get nothing.

If label is specified, then the control must have this label. Note that radio controls and checkboxes never have labels β€” their items do. the lore πŸ’€


fixup()

Normalises the form after all controls have been added 🧼✨

This is usually called by ParseFile and ParseResponse. Don't call it yourself unless you're building your own Control instances. seriously. hands off. πŸ™ˆ

This method should only be called once, after all controls have been added to the form. one and done, bestie.


get_value(name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None)

Returns the value of a control πŸ’–

If only name and value arguments are supplied, it's equivalent to:

form[name]

get_value_by_label(name=None, type=None, kind=None, id=None, label=None, nr=None)

All arguments should be passed by name. that's the whole instruction. pass them by name. 🌸


new_control(type, name, attrs, ignore_unknown=False, select_default=False, index=None)

Adds a new control to the form 🌱

This is usually called by mechanize. Don't call it yourself unless you're building your own Control instances. same warning, same energy, respect it πŸ’…

Note that controls representing lists of items are built up from controls holding only a single list item. See mechanize.ListControl for further information β€” it's a whole construction arc, honestly.

Parameters:

  • type β€” type of control (see mechanize.Control for a list)
  • attrs β€” HTML attributes of control
  • ignore_unknown β€” if true, use a dummy Control instance for controls of unknown type; otherwise, use a TextControl
  • select_default β€” for RADIO and multiple-selection SELECT controls, pick the first item as the default if no 'selected' HTML attribute is present (this defaulting happens when the HTMLForm.fixup method is called)
  • index β€” index of corresponding element in HTML (see MoreFormTests.test_interspersed_controls for motivation πŸ‘€)

possible_items(name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None)

Bestie, this one hands you back a list of every single value the control you're pointing at could possibly take. That's it. That's the whole gift. 🎁 A full menu of options, no gatekeeping.

set(selected, item_name, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None)

Select or deselect the named list item. You name it, you flip it. πŸ’…

Parameters

  • selected β€” boolean selected state

set_single(selected, name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None)

Select or deselect the list item in a control that has only one item. Iconic, low-maintenance, one-item energy. πŸŽ€

If the control actually has multiple list items, ItemCountError gets raised. Rude? No. Just honest. 😭

This is purely a convenience method, so you don't have to know the item's name β€” because in these single-item controls the item name is usually something totally meaningless like "1" or "on". Not me memorizing "on" for no reason. πŸ™ˆ

For example, if a checkbox has a single item named "on", the following two calls are equivalent:

control.toggle("on")
control.toggle_single()

set_value(value, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None)

Sets the value of the control. ✨

If you only pass the name and value arguments, it's equivalent to:

form[name] = value

set_value_by_label(value, name=None, type=None, kind=None, id=None, label=None, nr=None)

All arguments should be passed by name, bestie. Every. Single. One. 🫢

toggle(item_name, name=None, type=None, kind=None, id=None, nr=None, by_label=False, label=None)

Toggles the selected state of the named list item. On? Off? Who knows β€” that's the toggle's business. πŸ’€

toggle_single(name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None)

Toggles the selected state of the list item in a control that has only one item. And the rest of the behavior? Same as mechanize.HTMLForm.set_single(). The way that consistency just works. 🌈


class mechanize.Control(type, name, attrs, index=None)

Bases: object

An HTML form control. The main character of this whole section. πŸ‘‘

An HTMLForm contains a sequence of Controls. The Controls inside an HTMLForm are accessed using the HTMLForm.find_control method or the HTMLForm.controls attribute.

Control instances are usually constructed using the ParseFile / ParseResponse functions. If you use those functions, you can just ignore the rest of this paragraph, fr fr. A Control is only properly initialised after the fixup method has been called. Actually, this is only strictly necessary for ListControl instances. It's necessary because ListControls are built up from ListControls that each contain only a single item, and their initial value(s) can only be known once the whole sequence is complete. It's giving ✨assembly required✨.

The types and values that are acceptable for assignment to the value attribute are defined by subclasses.

If the disabled attribute is true, this represents the state that browsers typically show by 'greying out' a control. And if disabled is true, the Control will raise AttributeError if you try to change its value. On top of that, the control will not be considered 'successful' as defined by the W3C HTML 4 standard β€” i.e. it contributes no data to the return value of the HTMLForm.click* methods. To enable a control, set the disabled attribute to a false value. πŸ”“

If the readonly attribute is true, the Control will raise AttributeError if you attempt to change its value. To make a control writable, set the readonly attribute to a false value.

All controls have the disabled and readonly attributes β€” not just the ones that might have HTML attributes of the same names. Everybody gets them. Periodt.

On assignment to the value attribute, the following exceptions are raised: TypeError, AttributeError (if the value attribute shouldn't be assigned to β€” because the control is disabled, for example) and ValueError.

If the name or value attributes are None, or the value is an empty list, or the control is disabled, then the control is not successful.

Public attributes:

Variables

  • type (str) β€” string describing type of control (see the keys of the HTMLForm.type2class dictionary for the allowable values) (readonly)
  • name (str) β€” name of control (readonly)
  • value β€” current value of control (subclasses may allow a single value, a sequence of values, or either)
  • disabled (bool) β€” disabled state
  • readonly (bool) β€” readonly state
  • id (str) β€” value of id HTML attribute

get_labels()

Returns all labels (Label instances) for this control. 🏷️

If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that they appear in the HTML.

pairs()

Returns a list of (key, value) pairs suitable for passing to urlencode.


class mechanize.ScalarControl(type, name, attrs, index=None)

Bases: mechanize._form_controls.Control

A control whose value is not restricted to one of a prescribed set. Free-spirited. Untamed. πŸ¦‹

Some ScalarControls don't accept any value attribute at all. Otherwise, it takes a single value, which must be string-like.

Additional read-only public attribute:

Variables

  • attrs (dict) β€” dictionary mapping the names of original HTML attributes of the control to their values

get_labels()

Returns all labels (Label instances) for this control.

If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that they appear in the HTML.

pairs()

Returns a list of (key, value) pairs suitable for passing to urlencode.


class mechanize.TextControl(type, name, attrs, index=None)

Bases: mechanize._form_controls.ScalarControl

A textual input control. The classic. The blueprint. πŸ’–

Covers HTML elements: INPUT/TEXT, INPUT/PASSWORD, INPUT/HIDDEN, TEXTAREA

get_labels()

Returns all labels (Label instances) for this control.

If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that they appear in the HTML.

pairs()

Returns a list of (key, value) pairs suitable for passing to urlencode.


class mechanize.FileControl(type, name, attrs, index=None)

Bases: mechanize._form_controls.ScalarControl

File upload with INPUT TYPE=FILE. πŸ“Ž

Heads up: the value attribute of a FileControl is always None. Use add_file` instead. No cap.

Additional public method: add_file()

add_file(file_object, content_type=None, filename=None)

Adds data from the specified file so it can be uploaded. If you specify them, content_type and filename get sent in the HTTP headers. ✨

get_labels()

Returns all labels (Label instances) for this control.

If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that they appear in the HTML.

pairs()

Returns a list of (key, value) pairs suitable for passing to urlencode.


class mechanize.IgnoreControl(type, name, attrs, index=None)

Bases: mechanize._form_controls.ScalarControl

The control that we're just... not interested in. It's giving not my problem. πŸ’…

Covers html elements: INPUT/RESET, BUTTON/RESET, INPUT/BUTTON, BUTTON/BUTTON

These controls are always unsuccessful, in the terminology of HTML 4 (i.e. they never require any information to be returned to the server).

BUTTON/BUTTON is used to generate events for script embedded in HTML.

The value attribute of IgnoreControl is always None.

get_labels()

Returns all labels (Label instances) for this control.

If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that they appear in the HTML.

pairs()

Returns a list of (key, value) pairs suitable for passing to urlencode.


class mechanize.ListControl(type, name, attrs={}, select_default=False, called_as_base_class=False, index=None)

Bases: mechanize._form_controls.Control

A control representing a sequence of items. A whole squad of items, bestie. πŸ‘―

The value attribute of a ListControl represents the successful list items in the control. And the successful list items are the ones that are selected and not disabled.

ListControl implements both list controls that take a length-1 value (single-selection) and those that take length > 1 values (multiple-selection).

ListControls accept sequence values only. Some controls only accept sequences of length 0 or 1 (RADIO, and single-selection SELECT). In those cases, ItemCountError is raised if len(sequence) > 1. CHECKBOXes and multiple-selection SELECTs (the ones having the "multiple" HTML attribute) accept sequences of any length.

Note the following mistake: control.value = some_value assert control.value == some_value # not necessarily true

The reason for this is that the value attribute always gives the list items in the order they were listed in the HTML. So don't be shocked when it comes back shuffled, babe. It's not being shady, it's just alphabetical-by-document. πŸ™ˆ

ListControl items can also be referred to by their labels instead of names. Use the label argument to .get(), and the .set_value_by_label(), .get_value_by_label() methods.

And now, the plot twist: note that, rather confusingly, though SELECT controls are represented in HTML by SELECT elements (which contain OPTION elements, representing individual list items), CHECKBOXes and RADIOs are not represented by any element. Instead, those controls are represented by a collection of INPUT elements. Wild, right? 😭 For example, this is a SELECT control, named "control1":

                 <select name="control1">
                 <option>foo</option>
                 <option value="1">bar</option>
                 </select>

and this one is a CHECKBOX control, named "control2":

                 <input type="checkbox" name="control2" value="foo" id="cbe1">
                 <input type="checkbox" name="control2" value="bar" id="cbe2">

The id attribute of a CHECKBOX or RADIO ListControl is always that of its first element (so like, "cbe1" up there πŸ‘†). That's just how it is bestie, don't fight it.

Additional read-only public attribute: multiple.


πŸ› οΈ the methods, one by one

  • fixup() β€” ListControls get built up out of component list items (which are also ListControls, it's turtles all the way down 🐒) while parsing happens. You gotta call this method after all the items have been added. Wanna know why it's required? Go read mechanize.ListControl, it explains the whole thing. I'm not repeating it, that's a you-and-the-docs moment.
  • get(name=None, label=None, id=None, nr=None, exclude_disabled=False) β€” returns an item by name or label, and disambiguates with nr if it's giving ambiguous ✨

All arguments must be passed by name, with the exception of name, which may be used as a positional argument.

If name is specified, then the item must have the indicated name.

If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (like, label="please choose" will match " Do please choose an item " β€” see how it's just vibing through the extra spaces? 🫢).

If id is specified, then the item must have the indicated id.

nr is an optional 0-based index of the items matching the query.

If nr is the default None value and more than item is found, raises AmbiguityError.

If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError.

Optionally excludes disabled items.

  • get_item_attrs(name, by_label=False, nr=None) β€” returns a dictionary of HTML attributes for a single ListControl item. πŸ“–

The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about β€” for example, the "alt" HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip, cute right?).

The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML. No cap.

  • get_item_disabled(name, by_label=False, nr=None) β€” gets the disabled state of a named list item in a ListControl.
  • get_items(name=None, label=None, id=None, exclude_disabled=False) β€” returns matching items by name or label.

For argument docs, see the docstring for .get() (it's literally right above you babe, scroll up πŸ’…).

  • get_labels() β€” returns all labels (Label instances) for this control.

If the control was surrounded by a <label> tag, that one will be the first label; all the other labels, connected by 'for' and 'id', are in the order that they appear in the HTML.

  • get_value_by_label() β€” returns the value of the control as given by normalized labels.
  • pairs() β€” returns a list of (key, value) pairs, suitable for passing straight to urlencode. πŸŽ€
  • possible_items(by_label=False) β€” Deprecated: returns the names or labels of all possible items.

Includes disabled items, which may be misleading for some use cases. Just a heads up, bestie ⚠️

  • set(selected, name, by_label=False, nr=None) β€” Deprecated: given a name or label and an optional disambiguating index nr, sets the matching item's selection to the bool value of selected.

Selecting items follows the behavior described in the docstring of the 'get' method.

If the item is disabled, or this control is disabled or readonly, raise AttributeError. Periodt. πŸ™…

  • set_all_items_disabled(disabled) β€” sets the disabled state of all list items in a ListControl.

Parameters:

  • disabled β€” boolean disabled state
  • set_item_disabled(disabled, name, by_label=False, nr=None) β€” sets the disabled state of a named list item in a ListControl.

Parameters:

  • disabled β€” boolean disabled state
  • set_single(selected, by_label=None) β€” Deprecated: sets the selection of the single item in this control.

Raises ItemCountError if the control does not contain only one item.

The by_label argument is ignored, and included only for backwards compatibility. Yeah. It's just... there. Sitting. Existing. 😭

  • set_value_by_label(value) β€” sets the value of the control by item labels.

value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels: it will not complain as long as all the ambiguous labels share the same item name (e.g. OPTION value). Iconic behaviour tbh πŸ‘‘

  • toggle(name, by_label=False, nr=None) β€” Deprecated: given a name or label and an optional disambiguating index nr, toggles the matching item's selection.

Selecting items follows the behavior described in the docstring of the 'get' method.

If the item is disabled, or this control is disabled or readonly, raise AttributeError.

  • toggle_single(by_label=None) β€” Deprecated: toggles the selection of the single item in this control.

Raises ItemCountError if the control does not contain only one item.

The by_label argument is ignored, and included only for backwards compatibility.


πŸ“» class mechanize.RadioControl

class mechanize.RadioControl(type, name, attrs, select_default=False, index=None)

Bases: mechanize._form_controls.ListControl

Covers:

  • INPUT/RADIO

Okay so here's the thing β€” RadioControl is literally ListControl's twin, it inherited the entire method set, so bestie, I'm giving you the full run-down again because nothing gets skipped on my watch πŸ¦‹

  • fixup() β€” ListControls are built up from component list items (which are also ListControls) during parsing. This method should be called after all items have been added. See mechanize.ListControl for the reason this is required.
  • get(name=None, label=None, id=None, nr=None, exclude_disabled=False) β€” returns an item by name or label, disambiguating if necessary with nr.

All arguments must be passed by name, with the exception of 'name', which may be used as a positional argument.

If name is specified, then the item must have the indicated name.

If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (e.g. label="please choose" will match " Do please choose an item ").

If id is specified, then the item must have the indicated id.

nr is an optional 0-based index of the items matching the query.

If nr is the default None value and more than item is found, raises AmbiguityError.

If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError.

Optionally excludes disabled items.

  • get_item_attrs(name, by_label=False, nr=None) β€” returns a dictionary of HTML attributes for a single ListControl item.

The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about β€” for example, the "alt" HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip).

The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML.

  • get_item_disabled(name, by_label=False, nr=None) β€” gets the disabled state of a named list item in a ListControl.
  • get_items(name=None, label=None, id=None, exclude_disabled=False) β€” returns matching items by name or label.

For argument docs, see the docstring for .get()

  • get_labels() β€” returns all labels (Label instances) for this control.

If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that appear in the HTML.

  • get_value_by_label() β€” returns the value of the control as given by normalized labels.
  • pairs() β€” returns a list of (key, value) pairs suitable for passing to urlencode.
  • possible_items(by_label=False) β€” Deprecated: returns the names or labels of all possible items.

Includes disabled items, which may be misleading for some use cases.

  • set(selected, name, by_label=False, nr=None) β€” Deprecated: given a name or label and an optional disambiguating index nr, sets the matching item's selection to the bool value of selected.

Selecting items follows the behavior described in the docstring of the 'get' method.

If the item is disabled, or this control is disabled or readonly, raise AttributeError.

  • set_all_items_disabled(disabled) β€” sets the disabled state of all list items in a ListControl.

Parameters:

  • disabled β€” boolean disabled state

set_item_disabled(disabled, name, by_label=False, nr=None) β€” flip the disabled flag on a named list item inside a ListControl.

  • disabled β€” boolean disabled state (so True/False, bestie, no vibes-based guessing πŸ’…)

set_single(selected, by_label=None) β€” Deprecated bestie, it's giving legacy energy. Sets the selection of the single item in this control.

Raises ItemCountError if the control does not contain only one item.

The by_label argument is literally ignored and only hanging around for backwards compatibility. πŸ™ˆ


set_value_by_label(value) β€” set the value of the control by item labels.

value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching happens, the original label text gets whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels: it will not complain as long as all ambiguous labels share the same item name (e.g. OPTION value). So chill, it's not gonna start drama if the labels overlap as long as the item names match. ✨


toggle(name, by_label=False, nr=None) β€” Deprecated 🌸 Given a name or label and optional disambiguating index nr, toggle the matching item's selection.

Selecting items follows the behavior described in the docstring of the get method.

If the item is disabled, or this control is disabled or readonly, raise AttributeError. No toggling for the forbidden ones. πŸ’€

toggle_single(by_label=None) β€” Deprecated ⭐ Toggle the selection of the single item in this control.

Raises ItemCountError if the control does not contain only one item.

The by_label argument is ignored, and included only for backwards compatibility. (Same story as before, it's just here so old code doesn't break, periodt.)


class mechanize.CheckboxControl(type, name, attrs, select_default=False, index=None)

Bases: mechanize._form_controls.ListControl

Covers:

INPUT/CHECKBOX

No cap, that's the whole vibe of this one. πŸŽ€


fixup() β€” ListControls are built up from component list items (which are also ListControls) during parsing. This method should be called after all items have been added. See mechanize.ListControl for the reason this is required. Basically: assemble the squad first, then call fixup. 🫢


get(name=None, label=None, id=None, nr=None, exclude_disabled=False) β€” return an item by name or label, disambiguating if necessary with nr.

All arguments must be passed by name, with the exception of name, which may be used as a positional argument.

If name is specified, then the item must have the indicated name.

If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (e.g. label="please choose" will match " Do please choose an item ").

If id is specified, then the item must have the indicated id.

nr is an optional 0-based index of the items matching the query.

If nr is the default None value and more than one item is found, raises AmbiguityError.

If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError.

Optionally excludes disabled items. πŸ”₯


get_item_attrs(name, by_label=False, nr=None) β€” return a dictionary of HTML attributes for a single ListControl item.

The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about β€” for example, the alt HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip).

The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML. So yeah, it's the receipts from the source. πŸ’…


get_item_disabled(name, by_label=False, nr=None) β€” get the disabled state of a named list item in a ListControl.


get_items(name=None, label=None, id=None, exclude_disabled=False) β€” return matching items by name or label.

For argument docs, see the docstring for .get() (scroll up bestie, it's all there πŸ¦‹)


get_labels() β€” return all labels (Label instances) for this control.

If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by for and id, are in the order that they appear in the HTML.


get_value_by_label() β€” return the value of the control as given by normalized labels.


pairs() β€” return a list of (key, value) pairs suitable for passing to urlencode. Perfect little snack for the query string. πŸ“


possible_items(by_label=False) β€” Deprecated πŸ’œ Return the names or labels of all possible items.

Includes disabled items, which may be misleading for some use cases. So like, heads up β€” it's not filtering out the unavailable ones, it's giving everything. πŸ™ˆ


set(selected, name, by_label=False, nr=None) β€” Deprecated 🌈 Given a name or label and optional disambiguating index nr, set the matching item's selection to the bool value of selected.

Selecting items follows the behavior described in the docstring of the get method.

If the item is disabled, or this control is disabled or readonly, raise AttributeError. Same energy as toggle, don't try it. πŸ’€

set_all_items_disabled(disabled) β€” set the disabled state of all list items in a ListControl.

  • disabled β€” boolean disabled state

set_item_disabled(disabled, name, by_label=False, nr=None) β€” set the disabled state of a named list item in a ListControl.

  • disabled β€” boolean disabled state

set_single(selected, by_label=None) β€” Deprecated ✨ Set the selection of the single item in this control.

Raises ItemCountError if the control does not contain only one item.

The by_label argument is ignored, and included only for backwards compatibility.


set_value_by_label(value) β€” set the value of the control by item labels.

value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels: it will not complain as long as all ambiguous labels share the same item name (e.g. OPTION value).


toggle(name, by_label=False, nr=None) β€” Deprecated πŸŽ€ Given a name or label and optional disambiguating index nr, toggle the matching item's selection.

Selecting items follows the behavior described in the docstring of the get method.

If the item is disabled, or this control is disabled or readonly, raise AttributeError.

toggle_single(by_label=None) β€” Deprecated πŸ’« Toggle the selection of the single item in this control.

Raises ItemCountError if the control does not contain only one item.

The by_label argument is ignored, and included only for backwards compatibility.


class mechanize.SelectControl(type, name, attrs, select_default=False, index=None)

Bases: mechanize._form_controls.ListControl

Covers:

SELECT (and OPTION)

OPTION 'values', in HTML parlance, are Item 'names' in mechanize parlance. Lowkey important to keep straight, bestie. πŸ‘‘

SELECT control values and labels are subject to some messy defaulting rules. For example, if the HTML representation of the control is:

<SELECT name=year>
    <OPTION value=0 label="2002">current year</OPTION>
    <OPTION value=1>2001</OPTION>
    <OPTION>2000</OPTION>
</SELECT>

The items, in order, have labels "2002", "2001" and "2000", whereas their names (the OPTION values) are "0", "1" and "2000" respectively. Note that the value of the last OPTION in this example defaults to its contents, as specified by RFC 1866, as do the labels of the second and third OPTIONs. It's giving ✨ automatic ✨, and honestly? Slay.

The OPTION labels are sometimes more meaningful than the OPTION values, which can make for more maintainable code. Fr fr, pick the readable one when you can. πŸ¦‹

Additional read-only public attribute: attrs

The attrs attribute is a dictionary of the original HTML attributes of the SELECT element. Other ListControls do not have this attribute, because in other cases the control as a whole does not correspond to any single HTML element. control.get(...).attrs may be used as usual to get at the HTML attributes of the HTML elements corresponding to individual list items (for SELECT controls, these are OPTION elements).

Another special case is that the Item.attrs dictionaries have a special key "contents" which does not correspond to any real HTML attribute, but rather contains the contents of the OPTION element:

<OPTION>this bit</OPTION>

fixup() β€” ListControls are built up from component list items (which are also ListControls) during parsing. This method should be called after all items have been added. See mechanize.ListControl for the reason this is required.


get(name=None, label=None, id=None, nr=None, exclude_disabled=False) β€” return an item by name or label, disambiguating if necessary with nr.

All arguments must be passed by name, with the exception of name, which may be used as a positional argument.

  • If name is specified, then the item must have the indicated name. No name, no match, periodt. πŸ’…
  • If label is specified, then the item must have a label whose whitespace-compressed, stripped, text substring-matches the indicated label string (like, label="please choose" will match " Do please choose an item " β€” yes bestie, it's flexible like that 🫢).
  • If id is specified, then the item must have the indicated id.
  • nr is an optional 0-based index of the items matching the query. Zero-based, so the first one is 0, not 1, don't come for me πŸ™ˆ
  • If nr is the default None value and more than item is found, raises AmbiguityError. Like, girl, which one?? 😭
  • If no item is found, or if items are found but nr is specified and not found, raises ItemNotFoundError. It's giving ghosted πŸ’€
  • Optionally excludes disabled items.

get_item_attrs(name, by_label=False, nr=None)

Return dictionary of HTML attributes for a single ListControl item. πŸŽ€

The HTML element types that describe list items are: OPTION for SELECT controls, INPUT for the rest. These elements have HTML attributes that you may occasionally want to know about β€” for example, the "alt" HTML attribute gives a text string describing the item (graphical browsers usually display this as a tooltip). So cute, so informative ✨

The returned dictionary maps HTML attribute names to values. The names and values are taken from the original HTML. No cap, straight from the source πŸ’–

get_item_disabled(name, by_label=False, nr=None)

Get disabled state of named list item in a ListControl. Is it off? Is it on? We're checking πŸ‘‘

get_items(name=None, label=None, id=None, exclude_disabled=False)

Return matching items by name or label. 🌸

For argument docs, see the docstring for .get() β€” yes, we're reusing, and honestly? Efficient. Slay.

get_labels()

Return all labels (Label instances) for this control. 🏷️

If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that appear in the HTML.

get_value_by_label()

Return the value of the control as given by normalized labels. Simple, clean, iconic πŸ’…

pairs()

Return list of (key, value) pairs suitable for passing to urlencode. This is the little glow-up that makes it postable 🌈

possible_items(by_label=False)

Deprecated: return the names or labels of all possible items.

Includes disabled items, which may be misleading for some use cases. Heads up bestie, disabled stuff shows up here too, so don't be fooled 😭

set(selected, name, by_label=False, nr=None)

Deprecated: given a name or label and optional disambiguating index nr, set the matching item's selection to the bool value of selected.

Selecting items follows the behavior described in the docstring of the 'get' method.

if the item is disabled, or this control is disabled or readonly, raise AttributeError. Like, you literally cannot, and it will tell you πŸ”₯

set_all_items_disabled(disabled)

Set disabled state of all list items in a ListControl. Mass vibe check, everyone's getting the same treatment πŸ’€

Parameters

  • disabled β€” boolean disabled state

set_item_disabled(disabled, name, by_label=False, nr=None)

Set disabled state of named list item in a ListControl. One specific item, one specific fate πŸŽ€

Parameters

  • disabled β€” boolean disabled state

set_single(selected, by_label=None)

Deprecated: set the selection of the single item in this control.

Raises ItemCountError if the control does not contain only one item. Like, it's called single for a reason, bestie 😀

by_label argument is ignored, and included only for backwards compatibility. It's just there to keep the old code happy, we don't ask questions 🫢

set_value_by_label(value)

Set the value of control by item labels. ✨

value is expected to be an iterable of strings that are substrings of the item labels that should be selected. Before substring matching is performed, the original label text is whitespace-compressed (consecutive whitespace characters are converted to a single space character) and leading and trailing whitespace is stripped. Ambiguous labels: it will not complain as long as all ambiguous labels share the same item name (e.g. OPTION value). So it's chill about it, but only under that condition πŸ‘‘

toggle(name, by_label=False, nr=None)

Deprecated: given a name or label and optional disambiguating index nr, toggle the matching item's selection.

Selecting items follows the behavior described in the docstring of the 'get' method.

if the item is disabled, or this control is disabled or readonly, raise AttributeError. Nope, not today, not ever πŸ’…

toggle_single(by_label=None)

Deprecated: toggle the selection of the single item in this control.

Raises ItemCountError if the control does not contain only one item.

by_label argument is ignored, and included only for backwards compatibility. Same deal as before, it's just hanging out for the old-timers 🌸


πŸ¦‹ class mechanize.SubmitControl(type, name, attrs, index=None)

Covers:

INPUT/SUBMIT BUTTON/SUBMIT

Members

Inherited-members

Show-inheritance


πŸŽ€ class mechanize.ImageControl(type, name, attrs, index=None)

Bases: mechanize._form_controls.SubmitControl

Covers:

INPUT/IMAGE

Coordinates are specified using one of the HTMLForm.click* methods. Yes, you click, it knows where. Main character energy πŸ‘‘

get_labels()

Return all labels (Label instances) for this control. 🏷️

If the control was surrounded by a <label> tag, that will be the first label; all other labels, connected by 'for' and 'id', are in the order that appear in the HTML.

pairs()

Return list of (key, value) pairs suitable for passing to urlencode. And that's the tea, ready to be sent 🌈

🧠 ADVANCED TOPICS 🧠

πŸ’– Thread safety πŸ’–

okay so bestie, listen: the global mechanize.urlopen() and mechanize.urlretrieve() functions are thread safe. slay. πŸŽ‰

BUT. the mechanize browser instances are not thread safe. not even a little. πŸ’€

so if you wanna use a mechanize Browser instance across multiple threads, clone it β€” use the copy.copy(browser_object) method. the clone shares the same, thread safe cookie jar, and has the same settings/handlers as the original, but all other state is not shared, which is exactly what makes the clone safe to use in a different thread. iconic behaviour, honestly. ✨

πŸŽ€ Using custom CA certificates πŸŽ€

mechanize supports the same mechanism for using custom CA certificates as python >= 2.7.9. to change the certificates a mechanize browser instance uses, just call the mechanize.Browser.set_ca_data() method on it. that's it, that's the whole vibe. πŸ’…

πŸ” Debugging πŸ”

hints for debugging programs that use mechanize. let's get into it, bestie. 🫢

πŸͺ Cookies πŸͺ

a common mistake is to use mechanize.urlopen(), and the .extract_cookies() and .add_cookie_header() methods on a cookie object themselves. nope nope nope. if you use mechanize.urlopen() (or OpenerDirector.open()), the module handles extraction and adding of cookies by itself, so you should not call .extract_cookies() or .add_cookie_header(). it's giving redundant. πŸ™ˆ

are you sure the server is sending you any cookies in the first place? maybe the server is keeping track of state in some other way (HIDDEN HTML form entries (possibly in a separate page referenced by a frame), URL-encoded session keys, IP address, HTTP Referer headers)? perhaps some embedded script in the HTML is setting cookies (see below)? turn on Logging. πŸ‘‘

when you .save() to or .load()/.revert() from a file, single-session cookies will expire unless you explicitly request otherwise with the ignore_discard argument. this may be your problem if you find cookies are going away after saving and loading. so real. 😭

import mechanize
cj = mechanize.LWPCookieJar()
opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cj))
mechanize.install_opener(opener)
r = mechanize.urlopen("http://foobar.com/")
cj.save("/some/file", ignore_discard=True, ignore_expires=True)

JavaScript code can set cookies; mechanize does not support this. see jsfaq. no cap. πŸ’€

🌸 General 🌸

Enable Logging. (say it with me πŸ—£οΈ)

sometimes, a server wants particular HTTP headers set to the values it expects. for example, the User-Agent header may need to be set (mechanize.Browser.set_header()) to a value like that of a popular browser. servers are so picky fr fr. 😀

check that the browser is able to do manually what you're trying to achieve programmatically. make sure that what you do manually is exactly the same as what you're trying to do from Python β€” you may simply be hitting a server bug that only gets revealed if you view pages in a particular order, for example. servers really said "main character energy only". 🎭

try comparing the headers and data that your program sends with those that a browser sends. often this will give you the clue you need. you can use the developer tools in any browser to see exactly what the browser sends and receives. lowkey a superpower. πŸ”₯

if nothing is obviously wrong with the requests your program is sending and you're out of ideas, you can reliably locate the problem by copying the headers that a browser sends, and then changing headers until your program stops working again. temporarily switch to explicitly sending individual HTTP headers (by calling .add_header(), or by using httplib directly). start by sending exactly the headers that Firefox or Chrome send. you may need to make sure that a valid session ID is sent β€” the one you got from your browser may no longer be valid. if that works, you can begin the tedious process of changing your headers and data until they match what your original code was sending. you should end up with a minimal set of changes. if you think that reveals a bug in mechanize, please report it. we love a bug report. 🫢

πŸ“œ Logging πŸ“œ

to enable logging to stdout:

import sys, logging
logger = logging.getLogger("mechanize")
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.DEBUG)

you can reduce the amount of information shown by setting the level to logging.INFO instead of logging.DEBUG, or by only enabling logging for one of the following logger names instead of "mechanize":

  • "mechanize": Everything. the whole menu. πŸ‘‘
  • "mechanize.cookies": Why particular cookies are accepted or rejected and why they are or are not returned. Requires logging enabled at the DEBUG level. πŸͺ
  • "mechanize.http_responses": HTTP response body data. πŸ“¦
  • "mechanize.http_redirects": HTTP redirect information. πŸ”€

πŸ“‘ HTTP headers πŸ“‘

an example showing how to enable printing of HTTP headers to stdout, logging of HTTP response bodies, and logging of information about redirections:

import sys, logging
import mechanize

logger = logging.getLogger("mechanize")
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.DEBUG)

browser = mechanize.Browser()
browser.set_debug_http(True)
browser.set_debug_responses(True)
browser.set_debug_redirects(True)
response = browser.open("http://python.org/")

alternatively, you can examine request and response objects to see what's going on. note that requests may involve "sub-requests" in cases such as redirection, in which case you will not see everything that's going on just by examining the original request and final response. sneaky little sub-requests. πŸ•΅οΈ


πŸš€ QUICKSTART πŸš€

the examples below are written for a website that does not exist (example.com), so cannot be run. yes bestie, it's a fictional website, we're just here for the vibes. ✨

import re
import mechanize

br = mechanize.Browser()
br.open("http://www.example.com/")
# follow second link with element text matching regular expression
response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1)
print(br.title())
print(response1.geturl())
print(response1.info())  # headers
print(response1.read())  # body

br.select_form(name="order")
# Browser passes through unknown attributes (including methods)
# to the selected HTMLForm.
br["cheeses"] = ["mozzarella", "caerphilly"]  # (the method here is __setitem__)
# Submit current form.  Browser calls .close() on the current response on
# navigation, so this closes response1
response2 = br.submit()

# print currently selected form (don't call .submit() on this, use br.submit())
print(br.form)

response3 = br.back()  # back to cheese shop (same data as response1)
# the history mechanism returns cached response objects
# we can still use the response, even though it was .close()d
response3.get_data()  # like .seek(0) followed by .read()
response4 = br.reload()  # fetches from server

for form in br.forms():
    print(form)
# .links() optionally accepts the keyword args of .follow_/.find_link()
for link in br.links(url_regex="python.org"):
    print(link)
    br.follow_link(link)  # takes EITHER Link instance OR keyword args
    br.back()

you may control the browser's policy by using the methods of mechanize.Browser's base class, mechanize.UserAgent. for example:

br = mechanize.Browser()
# Explicitly configure proxies (Browser will attempt to set good defaults).
# Note the userinfo ("joe:password@") and port number (":3128") are optional.
br.set_proxies({"http": "joe:password@myproxy.example.com:3128",
                "ftp": "proxy.example.com",
                })
# Add HTTP Basic/Digest auth username and password for HTTP proxy access.
# (equivalent to using "joe:password@..." form above)
br.add_proxy_password("joe", "password")
# Add HTTP Basic/Digest auth username and password for website access.
br.add_password("http://example.com/protected/", "joe", "password")
# Add an extra header to all outgoing requests, you can also
# re-order or remove headers in this function.
br.finalize_request_headers = lambda request, headers: headers.__setitem__(
  'My-Custom-Header', 'Something')
# Don't handle HTTP-EQUIV headers (HTTP headers embedded in HTML).
br.set_handle_equiv(False)
# Ignore robots.txt.  Do not do this without thought and consideration.
br.set_handle_robots(False)
# Don't add Referer (sic) header
br.set_handle_referer(False)
# Don't handle Refresh redirections
br.set_handle_refresh(False)
# Don't handle cookies
br.set_cookiejar()
# Supply your own mechanize.CookieJar (NOTE: cookie handling is ON by
# default: no need to do this unless you have some reason to use a
# particular cookiejar)
br.set_cookiejar(cj)
# Tell the browser to send the Accept-Encoding: gzip header to the server
# to indicate it supports gzip Content-Encoding
br.set_request_gzip(True)
# Do not verify SSL certificates
import ssl
br.set_ca_data(context=ssl._create_unverified_context(cert_reqs=ssl.CERT_NONE))
# Log information about HTTP redirects and Refreshes.
br.set_debug_redirects(True)
# Log HTTP response bodies (i.e. the HTML, most of the time).
br.set_debug_responses(True)
# Print HTTP headers.
br.set_debug_http(True)

# To make sure you're seeing all debug output:
logger = logging.getLogger("mechanize")
logger.addHandler(logging.StreamHandler(sys.stdout))
logger.setLevel(logging.INFO)

# Sometimes it's useful to process bad headers or bad HTML:
response = br.response()  # this is a copy of response
headers = response.info()  # this is a HTTPMessage
headers["Content-type"] = "text/html; charset=utf-8"
response.set_data(response.get_data().replace("<!---", "<!--"))
br.set_response(response)

mechanize exports the complete interface of urllib2:

import mechanize
response = mechanize.urlopen("http://www.example.com/")
print(response.read())

when using mechanize, anything you would normally import from urllib2 should be imported from mechanize instead. periodt. πŸ’…

  • genindex
  • modindex
  • search

πŸ‘‘ AUTHOR πŸ‘‘

Kovid Goyal

2021, Kovid Goyal


and that's a wrap on the whole entire manual, bestie!! πŸŽ‰πŸ¦‹ the source/version is 0.4.7, dated Dec 30, 2021, and it lives under MECHANIZE(1) β€” so if you see that footer floating around somewhere, that's us, that's the whole iconique era. go forth and scrape responsibly, you absolute legend. πŸ’–βœ¨πŸŒˆπŸ‘‘πŸ«Ά

πŸ“¦ where this page comes from