Debian Codegraph @

examples/forms/example.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python
2
3 from __future__ import print_function
4 import sys
5
6 import mechanize
7
8 if len(sys.argv) == 1:
9 uri = "http://wwwsearch.sourceforge.net/"
10 else:
11 uri = sys.argv[1]
12
13 br = mechanize.Browser()
14 br.open(mechanize.urljoin(uri, "mechanize/example.html"))
15 forms = list(br.forms())
16 # f = open("example.html")
17 # forms = mechanize.ParseFile(f, "http://example.com/example.html",
18 # backwards_compat=False)
19 # f.close()
20 form = forms[0]
21 print(form) # very useful!
22
23 # A 'control' is a graphical HTML form widget: a text entry box, a
24 # dropdown 'select' list, a checkbox, etc.
25
26 # Indexing allows setting and retrieval of control values
27 original_text = form["comments"] # a string, NOT a Control instance
28 form["comments"] = "Blah."
29
30 # Controls that represent lists (checkbox, select and radio lists) are
31 # ListControl instances. Their values are sequences of list item names.
32 # They come in two flavours: single- and multiple-selection:
33 form["favorite_cheese"] = ["brie"] # single
34 form["cheeses"] = ["parmesan", "leicester", "cheddar"] # multi
35 # equivalent, but more flexible:
36 form.set_value(["parmesan", "leicester", "cheddar"], name="cheeses")
37
38 # Add files to FILE controls with .add_file(). Only call this multiple
39 # times if the server is expecting multiple files.
40 # add a file, default value for MIME type, no filename sent to server
41 form.add_file(open("data.dat", 'rb'))
42 # add a second file, explicitly giving MIME type, and telling the server
43 # what the filename is
44 form.add_file(open("data.txt", 'rb'), "text/plain", "data.txt")
45
46 # All Controls may be disabled (equivalent of greyed-out in browser)...
47 control = form.find_control("comments")
48 print(control.disabled)
49 # ...or readonly
50 print(control.readonly)
51 # readonly and disabled attributes can be assigned to
52 control.disabled = False
53 # convenience method, used here to make all controls writable (unless
54 # they're disabled):
55 form.set_all_readonly(False)
56
57 # A couple of notes about list controls and HTML:
58
59 # 1. List controls correspond to either a single SELECT element, or
60 # multiple INPUT elements. Items correspond to either OPTION or INPUT
61 # elements. For example, this is a SELECT control, named "control1":
62
63 # <select name="control1">
64 # <option>foo</option>
65 # <option value="1">bar</option>
66 # </select>
67
68 # and this is a CHECKBOX control, named "control2":
69
70 # <input type="checkbox" name="control2" value="foo" id="cbe1">
71 # <input type="checkbox" name="control2" value="bar" id="cbe2">
72
73 # You know the latter is a single control because all the name attributes
74 # are the same.
75
76 # 2. Item names are the strings that go to make up the value that should
77 # be returned to the server. These strings come from various different
78 # pieces of text in the HTML. The HTML standard and the mechanize
79 # docstrings explain in detail, but playing around with an HTML file,
80 # ParseFile() and 'print form' is very useful to understand this!
81
82 # You can get the Control instances from inside the form...
83 control = form.find_control("cheeses", type="select")
84 print(control.name, control.value, control.type)
85 control.value = ["mascarpone", "curd"]
86 # ...and the Item instances from inside the Control
87 item = control.get("curd")
88 print(item.name, item.selected, item.id, item.attrs)
89 item.selected = False
90
91 # Controls may be referred to by label:
92 # find control with label that has a *substring* "Cheeses"
93 # (e.g., a label "Please select a cheese" would match).
94 control = form.find_control(label="select a cheese")
95
96 # You can explicitly say that you're referring to a ListControl:
97 # set value of "cheeses" ListControl
98 form.set_value(["gouda"], name="cheeses", kind="list")
99 # equivalent:
100 form.find_control(name="cheeses", kind="list").value = ["gouda"]
101 # the first example is also almost equivalent to the following (but
102 # insists that the control be a ListControl -- so it will skip any
103 # non-list controls that come before the control we want)
104 form["cheeses"] = ["gouda"]
105 # The kind argument can also take values "multilist", "singlelist", "text",
106 # "clickable" and "file":
107 # find first control that will accept text, and scribble in it
108 form.set_value("rhubarb rhubarb", kind="text", nr=0)
109 # find, and set the value of, the first single-selection list control
110 form.set_value(["spam"], kind="singlelist", nr=0)
111
112 # You can find controls with a general predicate function:
113
114
115 def control_has_caerphilly(control):
116 for item in control.items:
117 if item.name == "caerphilly":
118 return True
119
120
121 form.find_control(kind="list", predicate=control_has_caerphilly)
122
123 # HTMLForm.controls is a list of all controls in the form
124 for control in form.controls:
125 if control.value == "inquisition":
126 sys.exit()
127
128 # Control.items is a list of all Item instances in the control
129 for item in form.find_control("cheeses").items:
130 print(item.name)
131
132 # To remove items from a list control, remove it from .items:
133 cheeses = form.find_control("cheeses")
134 curd = cheeses.get("curd")
135 del cheeses.items[cheeses.items.index(curd)]
136 # To add items to a list container, instantiate an Item with its control
137 # and attributes:
138 # Note that you are responsible for getting the attributes correct here,
139 # and these are not quite identical to the original HTML, due to
140 # defaulting rules and a few special attributes (e.g. Items that represent
141 # OPTIONs have a special "contents" key in their .attrs dict). In future
142 # there will be an explicitly supported way of using the parsing logic to
143 # add items and controls from HTML strings without knowing these details.
144 mechanize.Item(cheeses, {"contents": "mascarpone",
145 "value": "mascarpone"})
146
147 # You can specify list items by label using set/get_value_by_label() and
148 # the label argument of the .get() method. Sometimes labels are easier to
149 # maintain than names, sometimes the other way around.
150 form.set_value_by_label(["Mozzarella", "Caerphilly"], "cheeses")
151
152 # Which items are present, selected, and successful?
153 # is the "parmesan" item of the "cheeses" control successful (selected
154 # and not disabled)?
155 print("parmesan" in form["cheeses"])
156 # is the "parmesan" item of the "cheeses" control selected?
157 print("parmesan" in [
158 item.name for item in form.find_control("cheeses").items if item.selected])
159 # does cheeses control have a "caerphilly" item?
160 print("caerphilly" in [
161 item.name for item in form.find_control("cheeses").items])
162
163 # Sometimes one wants to set or clear individual items in a list, rather
164 # than setting the whole .value:
165 # select the item named "gorgonzola" in the first control named "cheeses"
166 form.find_control("cheeses").get("gorgonzola").selected = True
167 # You can be more specific:
168 # deselect "edam" in third CHECKBOX control
169 form.find_control(type="checkbox", nr=2).get("edam").selected = False
170 # deselect item labelled "Mozzarella" in control with id "chz"
171 form.find_control(id="chz").get(label="Mozzarella").selected = False
172
173 # Often, a single checkbox (a CHECKBOX control with a single item) is
174 # present. In that case, the name of the single item isn't of much
175 # interest, so it's a good idea to check and uncheck the box without
176 # using the item name:
177 form.find_control("smelly").items[0].selected = True # check
178 form.find_control("smelly").items[0].selected = False # uncheck
179
180 # Items may be disabled (selecting or de-selecting a disabled item is
181 # not allowed):
182 control = form.find_control("cheeses")
183 print(control.get("emmenthal").disabled)
184 control.get("emmenthal").disabled = True
185 # enable all items in control
186 control.set_all_items_disabled(False)
187
188 request2 = form.click() # mechanize.Request object
189 try:
190 response2 = mechanize.urlopen(request2)
191 except mechanize.HTTPError as response2:
192 pass
193
194 print(response2.geturl())
195 # headers
196 for name, value in list(response2.info().items()):
197 if name != "date":
198 print("%s: %s" % (name.title(), value))
199 print(response2.read()) # body
200 response2.close()