<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <meta name="author" content="John J. Lee &lt;jjl@@pobox.com&gt;">
  <meta name="date" content="2005-01">
  <meta name="keywords" content="form,HTML,Python,web,client,client-side">
  <title>ClientForm</title>
  <style type="text/css" media="screen">@@import "../styles/style.css";</style>
  <base href="http://wwwsearch.sourceforge.net/ClientForm/">
</head>
<body>

@# This file is processed by EmPy to colorize Python source code
@# http://wwwsearch.sf.net/bits/colorize.py
@{from colorize import colorize}

<div id=sf><a href="http://sourceforge.net">
<img src="http://sourceforge.net/sflogo.php?group_id=48205&amp;type=2"
 width="125" height="37" alt="SourceForge.net Logo"></a></div>

<h1>ClientForm</h1>

<div id="Content">

<p>ClientForm is a Python module for handling HTML forms on the client
side, useful for parsing HTML forms, filling them in and returning the
completed forms to the server.  It developed from a port of Gisle Aas'
Perl module <code>HTML::Form</code>, from the <a
href="http://www.linpro.no/lwp/">libwww-perl</a> library, but the
interface is not the same.

<p>Simple example:

@{colorize(r"""
 from urllib2 import urlopen
 from ClientForm import ParseResponse

 forms = ParseResponse(urlopen("http://www.example.com/form.html"))
 form = forms[0]
 print form
 form["author"] = "Gisle Aas"

 # form.click() returns a urllib2.Request object
 # (see HTMLForm.click.__doc__ if you don't have urllib2)
 response = urlopen(form.click("Thanks"))
""")}

<p>A more complicated example:

@{colorize(r"""
 import ClientForm
 import urllib2
 request = urllib2.Request("http://www.example.com/form.html")
 response = urllib2.urlopen(request)
 forms = ClientForm.ParseResponse(response)
 response.close()
 form = forms[0]
 print form  # very useful!

 # Indexing allows setting and retrieval of control values
 original_text = form["comments"]  # a string, NOT a Control instance
 form["comments"] = "Blah."

 # Controls that represent lists (checkbox, select and radio lists) are
 # ListControls.  Their values are sequences of list item names.
 # They come in two flavours: single- and multiple-selection:
 print form.possible_items("cheeses")
 form["favorite_cheese"] = ["brie"]  # single
 form["cheeses"] = ["parmesan", "leicester", "cheddar"]  # multi
 #  is the "parmesan" item of the "cheeses" control selected?
 print "parmesan" in form["cheeses"]
 #  does cheeses control have a "caerphilly" item?
 print "caerphilly" in form.possible_items("cheeses")

 # Sometimes one wants to set or clear individual items in a list:
 #  select the item named "gorgonzola" in the first control named "cheeses"
 form.set(True, "gorgonzola", "cheeses")
 # You can be more specific: supply at least one of name, type, kind, id
 # and nr (most other methods on HTMLForm take the same form of arguments):
 #  deselect "edam" in third CHECKBOX control
 form.set(False, "edam", type="checkbox", nr=2)

 # You can explicitly say that you're referring to a ListControl:
 #  set whole value (rather than just one item of) "cheeses" ListControl
 form.set_value(["gouda"], name="cheeses", kind="list")
 #  last example is almost equivalent to following (but insists that the
 #  control be a ListControl -- so it will skip any non-list controls that
 #  come before the control we want)
 form["cheeses"] = ["gouda"]
 # The kind argument can also take values "multilist", "singlelist", "text",
 # "clickable" and "file":
 #  find first control that will accept text, and scribble in it
 form.set_value("rhubarb rhubarb", kind="text")
 form.set_value([""], kind="singlelist")

 # Often, a single checkbox (a CHECKBOX control with a single item) is
 # present.  In that case, the name of the single item isn't of much
 # interest, so it's useful to be able to check and uncheck the box
 # without using the item name:
 form.set_single(True, "smelly")  # check
 form.set_single(False, "smelly")  # uncheck

 # Add files to FILE controls with .add_file().  Only call this multiple
 # times if the server is expecting multiple files.
 #  add a file, default value for MIME type, no filename sent to server
 form.add_file(open("data.dat"))
 #  add a second file, explicitly giving MIME type, and telling the server
 #   what the filename is
 form.add_file(open("data.txt"), "text/plain", "data.txt")

 # Many methods have a by_label argument, allowing specification of list
 # items by label instead of by name.  At the moment, only SelectControl
 # supports this argument (this will be fixed).  Sometimes labels are
 # easier to maintain than names, sometimes the other way around.
 form.set_value(["Mozzarella", "Caerphilly"], "cheeses", by_label=True)

 # It's also possible to get at the individual controls inside the form.
 # This is useful for calling several methods in a row on a single control,
 # and for the less common operations.  The methods are quite similar to
 # those on HTMLForm:
 control = form.find_control("cheeses", type="select")
 print control.value, control.name, control.type
 print control.possible_items()
 control.value = ["mascarpone", "curd"]
 control.set(True, "limburger")

 # All Controls may be disabled (equivalent of greyed-out in browser)
 control = form.find_control("comments")
 print control.disabled
 # ...or readonly
 print control.readonly
 # readonly and disabled attributes can be assigned to
 control.disabled = False
 # convenience method, used here to make all controls writable (unless
 # they're disabled):
 form.set_all_readonly(False)
 # ListControl items may also be disabled (setting a disabled item is not
 # allowed, but clearing one is allowed):
 print control.get_item_disabled("emmenthal")
 control.set_item_disabled(True, "emmenthal")
 #  enable all items in control
 control.set_all_items_disabled(False)

 # HTMLForm.controls is a list of all controls in the form
 for control in form.controls:
     if control.value == "inquisition": sys.exit()

 request2 = form.click()  # urllib2.Request object
 response2 = urllib2.urlopen(request2)

 print response2.geturl()
 print response2.info()  # headers
 print response2.read()  # body
 response2.close()
""")}

<p>All of the standard control types are supported: <code>TEXT</code>,
<code>PASSWORD</code>, <code>HIDDEN</code>, <code>TEXTAREA</code>,
<code>ISINDEX</code>, <code>RESET</code>, <code>BUTTON</code> (<code>INPUT
TYPE=BUTTON</code> and the various <code>BUTTON</code> types),
<code>SUBMIT</code>, <code>IMAGE</code>, <code>RADIO</code>,
<code>CHECKBOX</code>, <code>SELECT</code>/<code>OPTION</code> and
<code>FILE</code> (for file upload).  Both standard form encodings
(<code>application/x-www-form-urlencoded</code> and
<code>multipart/form-data</code>) are supported.

<p>The module is designed for testing and automation of web
interfaces, not for implementing interactive user agents.

<p><strong><em>Security note</em>: Remember that any passwords you store in
<code>HTMLForm</code> 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 <code>HTMLForm</code> objects.  You could also pickle before
filling in any password, or just set the password to <code>""</code> before
pickling.</strong>

<p>Python 1.5.2 or above is required.  To run the tests, you need the
<code>unittest</code> module (from <a href="http://pyunit.sourceforge.net/">PyUnit</a>).
<code>unittest</code> is a standard library module with Python 2.1 and
above.

<p>For full documentation, see the docstrings in ClientForm.py.

<p><em><strong>Note: this page describes the 0.1.x interface.  See <a
href="./src/README_0_0_15.html">here</a> for the old 0.0.x interface.</strong>
</em>


<a name="download"></a>
<h2>Download</h2>

<p>For installation instructions, see the INSTALL file included in the
distribution. 

<p><em>Stable release.</em>.  There have been many interface changes since
0.0.x, so I don't recommend upgrading old code from 0.0.x unless you want the
new features.

<p>0.1.x includes <code>FILE</code> control support for file upload, handling
of disabled list items, and a redesigned interface.
<ul>
<li><a href="./src/ClientForm-0.1.17.tar.gz">ClientForm-0.1.17.tar.gz</a>
<li><a href="./src/ClientForm-0_1_17.zip">ClientForm-0_1_17.zip</a>
<li><a href="./src/ChangeLog.txt">Change Log</a> (included in distribution)
<li><a href="./src/">Older versions.</a>
</ul>

<br>

<p><em>Old release.</em>
<ul>
<li><a href="./src/ClientForm-0.0.16.tar.gz">ClientForm-0.0.16.tar.gz</a>
<li><a href="./src/ClientForm-0_0_16.zip">ClientForm-0_0_16.zip</a>
<li><a href="./src/ChangeLog.txt">Change Log</a> (included in distribution)
<li><a href="./src/">Older versions.</a>
</ul>


<a name="faq"></a>
<h2>FAQs</h2>
<ul>
  <li>Doesn't the standard Python library module, <code>cgi</code>, do this?
  <p>No: the <code>cgi</code> module does the server end of the job.  It
     doesn't know how to parse or fill in a form or how to send it back to the
     server.
  <li>Which version of Python do I need?
  <p>1.5.2 or above.
  <li>Is <code>urllib2</code> required?
  <p>No.
  <li>How do I use it without <code>urllib2</code>?
  <p>Use <code>.click_request_data()</code> instead of <code>.click()</code>.
  <li>Which <code>urllib2</code> do I need?
  <p>You don't.  It's convenient, though.  If you have Python 2.0, you need to
     upgrade to the version from Python 2.1 (available from <a
     href="http://www.python.org/">www.python.org</a>).  Alternatively, use the
     1.5.2-compatible version.  If you have Python 1.5.2, use this <a
     href="../bits/urllib2.py"><code>urllib2</code></a> and <a
     href="../bits/urllib.py"><code>urllib</code></a>. Otherwise, you're OK.
  <li>Which license?
  <p>The <a href="http://www.opensource.org/licenses/bsd-license.php"> BSD
     license</a> (included in distribution).

  <li>Is XHTML supported?
  <p>Yes, since 0.1.12.
  <li>How do I figure out what control names and values to use?
  <p><code>print form</code> is usually all you need.
     <code>HTMLForm.possible_items</code> can be useful.  Note that it's
     possible to use item labels instead of item names, which can be useful
     &mdash; use the <code>by_label</code> arguments to the various methods,
     and the <code>.get_value_by_label()</code> /
     <code>.set_value_by_label()</code> methods on <code>ListControl</code>.
     Only <code>SelectControl</code> currently supports item labels (which
     default to <code>OPTION</code> element contents).  I might not bother to
     fix this, since it seems it's probably only useful for <code>SELECT</code>
     anyway.
  <li>What do those <code>'*'</code> characters mean in the string
     representations of list controls?
  <p>A <code>*</code> next to an item means that item is selected.
  <li>What do those parentheses (round brackets) mean in the string
     representations of list controls?
  <p>Parentheses <code>(foo)</code> around an item mean that item is disabled.
  <li>Why doesn't &lt;some control&gt; turn up in the data returned by
     <code>.click*()</code> when that control has non-<code>None</code> value?
  <p>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.
  <li>Why does ClientForm not follow the HTML 4.0 / RFC 1866 standards for
     <code>RADIO</code> and multiple-selection <code>SELECT</code> controls?
  <p>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. Use the <code>select_default</code> argument to
     <code>ParseResponse</code> if you want to follow the RFC 1866 rules
     instead.  Note that browser behaviour violates the HTML 4.01 specification
     in the case of <code>RADIO</code> controls.
  <li>Why does <code>.click()</code>ing on a button not work for me?
    <ul>
    <li>Clicking on a <code>RESET</code> 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 <code>RESET</code> sends
        nothing to the server, so there is little point in having
        <code>.click()</code> do anything special here.
    <li>Clicking on a <code>BUTTON TYPE=BUTTON</code> doesn't do anything
        either, also by design.  This time, the reason is that that
        <code>BUTTON</code> is only in the HTML standard so that one can attach
        callbacks to its events.  The callbacks are functions in
        <code>SCRIPT</code> elements (such as Javascript) embedded in the HTML,
        and their execution may result in information getting sent back to the
        server.  ClientForm, however, knows nothing about these callbacks, so
        it can't do anything useful with a click on a <code>BUTTON</code> whose
        type is <code>BUTTON</code>.
    <li>Generally, embedded script may be messing things up in all kinds of
        ways.  See the answer to the next question.
    </ul>
  <li>Embedded script is messing up my form filling.  What do I do?
  <p>See the <a href="../bits/GeneralFAQ.html">General FAQs</a> page for
     what to do about this.
<!-- XXX example here -->
  <li>I'm having trouble debugging my code.
  <p>The <a href="../ClientCookie/">ClientCookie</a> package makes it
     easy to get <code>.seek()</code>able response objects, which is
     convenient for debugging.  See also <a
     href="../ClientCookie/doc.html#debugging">here</a> for few
     relevant tips.  Also see <a href="../bits/GeneralFAQ.html"> General
     FAQs</a>.
  <li>I have a control containing a list of integers.  How do I select the one
     whose value is nearest to the one I want?
<p>@{colorize(r"""
 import bisect
 def closest_int_value(form, ctrl_name, value):
     values = map(int, form.possible_items(ctrl_name))
     return str(values[bisect.bisect(values, value) - 1])

 form["distance"] = [closest_int_value(form, "distance", 23)]
""")}
  </li>
  <li>Where can I find out more about the HTML and HTTP standards?
  <ul>
     <li>W3C <a href="http://www.w3.org/TR/html401/">HTML 4.01
        Specification</a>.
     <li><a href="http://www.ietf.org/rfc/rfc1866.txt">RFC 1866</a> -
        the HTML 2.0 standard.
     <li><a href="http://www.ietf.org/rfc/rfc1867.txt">RFC 1867</a> -
        Form-based file upload.
     <li><a href="http://www.ietf.org/rfc/rfc2616.txt">RFC 2616</a> -
        HTTP 1.1 Specification.
  </ul>
</ul>

<p><a href="mailto:jjl@@pobox.com">John J. Lee</a>, January 2005.

</div>

<div id="Menu">

<a href="..">Home</a><br>
<!--<a href=""></a><br>-->

<br>

<a href="../ClientCookie/">ClientCookie</a><br>
<span class="thispage">ClientForm</span><br>
<a href="../DOMForm/">DOMForm</a><br>
<a href="../python-spidermonkey/">python-spidermonkey</a><br>
<a href="../ClientTable/">ClientTable</a><br>
<a href="../mechanize/">mechanize</a><br>
<a href="../pullparser/">pullparser</a><br>
<a href="../bits/GeneralFAQ.html">General FAQs</a><br>
<a href="../bits/urllib2_152.py">1.5.2 urllib2.py</a><br>
<a href="../bits/urllib_152.py">1.5.2 urllib.py</a><br>

<br>

<a href="../#other">Other stuff</a><br>

<br>

<a href="./#download">Download</a><br>
<a href="./#faq">FAQs</a><br>

</div>

</body>
</html>
