HTML Forms API

Forms in HTML documents are represented by mechanize.HTMLForm. Every form is a collection of controls. 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)[source]

Represents a single HTML <form> … </form> element.

A form consists of a sequence of controls that usually have names, and which 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 returned 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 for integration with third-party code).

Usually, HTMLForm instances are not created directly. Instead, they are automatically created when visting a page with a mechanize Browser. If you do construct HTMLForm objects yourself, however, note that 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. Assignment to a form index (form[“control_name”] = something) is equivalent to assignment 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 as 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 assigned list 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 the control to be operated on: see mechanize.HTMLForm.find_control().

ControlNotFoundError (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 (subclass of ValueError) is raised if a list item can’t be found. ItemCountError (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 – full (absolute URI) form action
  • method – “GET” or “POST”
  • enctype – form transfer encoding MIME type
  • name – name of form (None if no name was specified)
  • attrs – dictionary mapping original HTML form attributes to their values
  • controls – list of Control instances; do not alter this list (instead, call form.new_control to make a Control and add it to the form, or control.add_to_form if you already have a Control instance)

Methods for form filling:

Most of the these methods have very similar arguments. See mechanize.HTMLForm.find_control() for details of the name, type, kind, label and nr arguments.

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)
add_file(file_object, content_type=None, filename=None, name=None, id=None, nr=None, label=None)[source]

Add a file to be uploaded.

Parameters:
  • file_object – file-like object (with read method) from which to read data to upload
  • content_type – MIME content type of data to upload
  • filename – filename to pass to server

If filename is None, no filename is sent to the server.

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

At the moment, guessed content type is always application/octet-stream.

Note the following useful HTML attributes of file upload controls (see HTML 4.01 spec, section 17):

  • accept: 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 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)[source]

Clear the value attribute of a control.

As a result, the affected control will not be successful until a value is subsequently set. AttributeError is raised on readonly controls.

clear_all()[source]

Clear the value attributes of all controls in the form.

See mechanize.HTMLForm.clear()

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

Return request that would result from clicking on a control.

The request object is a mechanize.Request instance, which you can pass to mechanize.urlopen.

Only some control types (INPUT/SUBMIT & BUTTON/SUBMIT buttons and IMAGEs) can be clicked.

Will click on the first clickable control, subject to the name, type and nr arguments (as for find_control). If no name, type, id or number is specified and there are no clickable controls, a request will be returned for the form in its current, un-clicked, state.

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.

You can optionally specify a coordinate to click at, which only makes a difference if you clicked on an image.

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

As for click_request_data, but 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 this should not be necessary. Otherwise, use the click method.

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 are not using mechanize, use click_request_data.

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

As for click method, but return 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.

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

Locate and return some specific control within the form.

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

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”).

If kind is specified, then the control must fall into the specified group, each of which satisfies a particular interface. The types 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.

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. If no nr is supplied, AmbiguityError is raised if multiple controls match the other arguments.

If label is specified, then the control must have this label. Note that radio controls and checkboxes never have labels: their items do.

fixup()[source]

Normalise form after all controls have been added.

This is usually called by ParseFile and ParseResponse. Don’t call it youself unless you’re building your own Control instances.

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

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

Return value of control.

If only name and value arguments are supplied, equivalent to

form[name]
get_value_by_label(name=None, type=None, kind=None, id=None, label=None, nr=None)[source]

All arguments should be passed by name.

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

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.

Note that controls representing lists of items are built up from controls holding only a single list item. See mechanize.ListControl for further information.

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)[source]

Return a list of all values that the specified control can take.

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

Select / deselect named list item.

Parameters:selected – boolean selected state
set_single(selected, name=None, type=None, kind=None, id=None, nr=None, by_label=None, label=None)[source]

Select / deselect list item in a control having only one item.

If the control has multiple list items, ItemCountError is raised.

This is just a convenience method, so you don’t need to know the item’s name – the item name in these single-item controls is usually something meaningless like “1” or “on”.

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)[source]

Set value of control.

If only name and value arguments are supplied, equivalent to

form[name] = value
set_value_by_label(value, name=None, type=None, kind=None, id=None, label=None, nr=None)[source]

All arguments should be passed by name.

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

Toggle selected state of named list item.

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

Toggle selected state of list item in control having only one item.

The rest is as for mechanize.HTMLForm.set_single()

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

An HTML form control.

An HTMLForm contains a sequence of Controls. The Controls in 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 ignore the rest of this paragraph. A Control is only properly initialised after the fixup method has been called. In fact, this is only strictly necessary for ListControl instances. This is necessary because ListControls are built up from ListControls each containing only a single item, and their initial value(s) can only be known after the sequence is complete.

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 typically represented by browsers by ‘greying out’ a control. If the disabled attribute is true, the Control will raise AttributeError if an attempt is made to change its value. In addition, the control will not be considered ‘successful’ as defined by the W3C HTML 4 standard – ie. it will contribute 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 an attempt is made 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 only those that may have the HTML attributes of the same names.

On assignment to the value attribute, the following exceptions are raised: TypeError, AttributeError (if the value attribute should not 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 if the control is disabled, 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()[source]

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()[source]

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

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

Bases: mechanize._form_controls.Control

Control whose value is not restricted to one of a prescribed set.

Some ScalarControls don’t accept any value attribute. Otherwise, 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()

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.

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

Bases: mechanize._form_controls.ScalarControl

Textual input control.

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

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.

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

Bases: mechanize._form_controls.ScalarControl

File upload with INPUT TYPE=FILE.

The value attribute of a FileControl is always None. Use add_file instead.

Additional public method: add_file()

add_file(file_object, content_type=None, filename=None)[source]

Add data from the specified file to be uploaded. content_type and filename are sent in the HTTP headers if specified.

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.

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

Bases: mechanize._form_controls.ScalarControl

Control that we’re not interested in.

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

These controls are always unsuccessful, in the terminology of HTML 4 (ie. 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()

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.

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

Bases: mechanize._form_controls.Control

Control representing a sequence of items.

The value attribute of a ListControl represents the successful list items in the control. The successful list items are those 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 (those 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.

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.

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. For example, this is a SELECT control, named “control1”:

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

and this 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 (for example, “cbe1” above).

Additional read-only public attribute: multiple.

fixup()[source]

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)[source]

Return 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)[source]

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).

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)[source]

Get disabled state of named list item in a ListControl.

get_items(name=None, label=None, id=None, exclude_disabled=False)[source]

Return matching items by name or label.

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

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()[source]

Return the value of the control as given by normalized labels.

pairs()

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

possible_items(by_label=False)[source]

Deprecated: return 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)[source]

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.

set_all_items_disabled(disabled)[source]

Set disabled state of all list items in a ListControl.

Parameters:disabled – boolean disabled state
set_item_disabled(disabled, name, by_label=False, nr=None)[source]

Set disabled state of named list item in a ListControl.

Parameters:disabled – boolean disabled state
set_single(selected, by_label=None)[source]

Deprecated: set 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.

set_value_by_label(value)[source]

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).

toggle(name, by_label=False, nr=None)[source]

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)[source]

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.

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

Bases: mechanize._form_controls.ListControl

Covers:

INPUT/RADIO

get(name=None, label=None, id=None, nr=None, exclude_disabled=False)

Return 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)

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).

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)

Get disabled state of 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()

get_value_by_label()

Return the value of the control as given by normalized labels.

pairs()

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

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.

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.

set_all_items_disabled(disabled)

Set disabled state of all list items in a ListControl.

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.

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.

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

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).

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.

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

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

Bases: mechanize._form_controls.ListControl

Covers:

INPUT/CHECKBOX

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 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)

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).

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)

Get disabled state of 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()

get_value_by_label()

Return the value of the control as given by normalized labels.

pairs()

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

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.

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.

set_all_items_disabled(disabled)

Set disabled state of all list items in a ListControl.

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.

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.

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

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).

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.

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

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

Bases: mechanize._form_controls.ListControl

Covers:

SELECT (and OPTION)

OPTION ‘values’, in HTML parlance, are Item ‘names’ in mechanize parlance.

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.

The OPTION labels are sometimes more meaningful than the OPTION values, which can make for more maintainable code.

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>
get(name=None, label=None, id=None, nr=None, exclude_disabled=False)

Return 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)

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).

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)

Get disabled state of 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()

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.

pairs()

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

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.

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.

set_all_items_disabled(disabled)

Set disabled state of all list items in a ListControl.

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.

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.

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

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).

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.

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

class mechanize.SubmitControl(type, name, attrs, index=None)[source]

Covers:

INPUT/SUBMIT BUTTON/SUBMIT

Members:
Inherited-members:
 
Show-inheritance:
 
class mechanize.ImageControl(type, name, attrs, index=None)[source]

Bases: mechanize._form_controls.SubmitControl

Covers:

INPUT/IMAGE

Coordinates are specified using one of the HTMLForm.click* methods.

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.