Debian Codegraph @

mechanize/_form_controls.py

raw symbols SCIP
1 #!/usr/bin/env python
2 # vim:fileencoding=utf-8
3 from __future__ import absolute_import
4
5 import random
6 import re
7 import sys
8 import warnings
9 from io import BytesIO
10 from mimetypes import guess_type
11
12 from . import _request
13 from .polyglot import (as_unicode, is_py2, iteritems, unicode_type, urlencode,
14 urlparse, urlunparse)
15
16 if is_py2:
17 from cStringIO import StringIO
18 else:
19 class StringIO(BytesIO):
20
21 def write(self, x):
22 if isinstance(x, str):
23 x = x.encode('utf-8')
24 BytesIO.write(self, x)
25
26
27 class Missing:
28 pass
29
30
31 class LocateError(ValueError):
32 pass
33
34
35 class AmbiguityError(LocateError):
36 pass
37
38
39 class ControlNotFoundError(LocateError):
40 pass
41
42
43 class ItemNotFoundError(LocateError):
44 pass
45
46
47 class ItemCountError(ValueError):
48 pass
49
50
51 _compress_re = re.compile(r"\s+")
52
53
54 def deprecation(message, stack_offset=0):
55 warnings.warn(message, DeprecationWarning, stacklevel=3 + stack_offset)
56
57
58 def compress_whitespace(text):
59 return re.sub(r'\s+', ' ', text or '').strip()
60
61
62 def isstringlike(x):
63 if isinstance(x, (bytes, unicode_type)):
64 return True
65 try:
66 x + ""
67 return True
68 except Exception:
69 return False
70
71
72 def choose_boundary():
73 """Return a string usable as a multipart boundary."""
74 # follow IE and firefox
75 limit = (1 << 31) - 1
76 nonce = "".join(str(random.randint(0, limit)) for i in (0, 1, 2))
77 return "-" * 27 + nonce
78
79
80 # This cut-n-pasted MimeWriter from standard library is here so can add
81 # to HTTP headers rather than message body when appropriate. It also uses
82 # \r\n in place of \n. This is a bit nasty.
83 class MimeWriter:
84 """Generic MIME writer.
85
86 Methods:
87
88 __init__()
89 addheader()
90 flushheaders()
91 startbody()
92 startmultipartbody()
93 nextpart()
94 lastpart()
95
96 A MIME writer is much more primitive than a MIME parser. It
97 doesn't seek around on the output file, and it doesn't use large
98 amounts of buffer space, so you have to write the parts in the
99 order they should occur on the output file. It does buffer the
100 headers you add, allowing you to rearrange their order.
101
102 General usage is:
103
104 .. code-block:: python
105
106 f = <open the output file>
107 w = MimeWriter(f)
108 ...call w.addheader(key, value) 0 or more times...
109
110 followed by either:
111
112 .. code-block:: python
113
114 f = w.startbody(content_type)
115 ...call f.write(data) for body data...
116
117 or:
118
119 .. code-block:: python
120
121 w.startmultipartbody(subtype)
122 for each part:
123 subwriter = w.nextpart()
124 ...use the subwriter's methods to create the subpart...
125 w.lastpart()
126
127 The subwriter is another MimeWriter instance, and should be
128 treated in the same way as the toplevel MimeWriter. This way,
129 writing recursive body parts is easy.
130
131 Warning: don't forget to call lastpart()!
132
133 XXX There should be more state so calls made in the wrong order
134 are detected.
135
136 Some special cases:
137
138 - startbody() just returns the file passed to the constructor;
139 but don't use this knowledge, as it may be changed.
140
141 - startmultipartbody() actually returns a file as well;
142 this can be used to write the initial 'if you can read this your
143 mailer is not MIME-aware' message.
144
145 - If you call flushheaders(), the headers accumulated so far are
146 written out (and forgotten); this is useful if you don't need a
147 body part at all, e.g. for a subpart of type message/rfc822
148 that's (mis)used to store some header-like information.
149
150 - Passing a keyword argument 'prefix=<flag>' to addheader(),
151 start*body() affects where the header is inserted; 0 means
152 append at the end, 1 means insert at the start; default is
153 append for addheader(), but insert for start*body(), which use
154 it to determine where the Content-type header goes.
155
156 """
157
158 def __init__(self, fp, http_hdrs=None):
159 self._http_hdrs = http_hdrs
160 self._fp = fp
161 self._headers = []
162 self._boundary = []
163 self._first_part = True
164
165 def addheader(self, key, value, prefix=0, add_to_http_hdrs=0):
166 """
167 prefix is ignored if add_to_http_hdrs is true.
168 """
169 lines = value.split("\r\n")
170 while lines and not lines[-1]:
171 del lines[-1]
172 while lines and not lines[0]:
173 del lines[0]
174 if add_to_http_hdrs:
175 value = "".join(lines)
176 # 2.2 urllib2 doesn't normalize header case
177 self._http_hdrs.append((key.capitalize(), value))
178 else:
179 for i in range(1, len(lines)):
180 lines[i] = " " + lines[i].strip()
181 value = "\r\n".join(lines) + "\r\n"
182 line = key.title() + ": " + value
183 if prefix:
184 self._headers.insert(0, line)
185 else:
186 self._headers.append(line)
187
188 def flushheaders(self):
189 for line in self._headers:
190 self._fp.write(line)
191 self._headers = []
192
193 def startbody(self,
194 ctype=None,
195 plist=[],
196 prefix=1,
197 add_to_http_hdrs=0,
198 content_type=1):
199 """
200 prefix is ignored if add_to_http_hdrs is true.
201 """
202 if content_type and ctype:
203 for name, value in plist:
204 ctype = ctype + ';\r\n %s=%s' % (name, value)
205 self.addheader(
206 "Content-Type",
207 ctype,
208 prefix=prefix,
209 add_to_http_hdrs=add_to_http_hdrs)
210 self.flushheaders()
211 if not add_to_http_hdrs:
212 self._fp.write("\r\n")
213 self._first_part = True
214 return self._fp
215
216 def startmultipartbody(self,
217 subtype,
218 boundary=None,
219 plist=[],
220 prefix=1,
221 add_to_http_hdrs=0,
222 content_type=1):
223 boundary = boundary or choose_boundary()
224 self._boundary.append(boundary)
225 return self.startbody(
226 "multipart/" + subtype, [("boundary", boundary)] + plist,
227 prefix=prefix,
228 add_to_http_hdrs=add_to_http_hdrs,
229 content_type=content_type)
230
231 def nextpart(self):
232 boundary = self._boundary[-1]
233 if self._first_part:
234 self._first_part = False
235 else:
236 self._fp.write("\r\n")
237 self._fp.write("--" + boundary + "\r\n")
238 return self.__class__(self._fp)
239
240 def lastpart(self):
241 if self._first_part:
242 self.nextpart()
243 boundary = self._boundary.pop()
244 self._fp.write("\r\n--" + boundary + "--\r\n")
245
246
247 class Label:
248 def __init__(self, text, for_id=None):
249 self.id = for_id
250 self.text = compress_whitespace(text or '')
251
252 def __repr__(self):
253 return "<Label(id=%r, text=%r)>" % (self.id, self.text)
254
255 __str__ = __repr__
256
257
258 def _get_label(attrs):
259 text = attrs.get("__label")
260 if text is not None:
261 return Label(text)
262
263
264 class Control:
265 """An HTML form control.
266
267 An HTMLForm contains a sequence of Controls. The Controls in an HTMLForm
268 are accessed using the HTMLForm.find_control method or the
269 HTMLForm.controls attribute.
270
271 Control instances are usually constructed using the ParseFile /
272 ParseResponse functions. If you use those functions, you can ignore the
273 rest of this paragraph. A Control is only properly initialised after the
274 fixup method has been called. In fact, this is only strictly necessary for
275 ListControl instances. This is necessary because ListControls are built up
276 from ListControls each containing only a single item, and their initial
277 value(s) can only be known after the sequence is complete.
278
279 The types and values that are acceptable for assignment to the value
280 attribute are defined by subclasses.
281
282 If the disabled attribute is true, this represents the state typically
283 represented by browsers by 'greying out' a control. If the disabled
284 attribute is true, the Control will raise AttributeError if an attempt is
285 made to change its value. In addition, the control will not be considered
286 'successful' as defined by the W3C HTML 4 standard -- ie. it will
287 contribute no data to the return value of the HTMLForm.click* methods. To
288 enable a control, set the disabled attribute to a false value.
289
290 If the readonly attribute is true, the Control will raise AttributeError if
291 an attempt is made to change its value. To make a control writable, set
292 the readonly attribute to a false value.
293
294 All controls have the disabled and readonly attributes, not only those that
295 may have the HTML attributes of the same names.
296
297 On assignment to the value attribute, the following exceptions are raised:
298 TypeError, AttributeError (if the value attribute should not be assigned
299 to, because the control is disabled, for example) and ValueError.
300
301 If the name or value attributes are None, or the value is an empty list, or
302 if the control is disabled, the control is not successful.
303
304 Public attributes:
305
306 :ivar str type: string describing type of control (see the keys of the
307 HTMLForm.type2class dictionary for the allowable values) (readonly)
308 :ivar str name: name of control (readonly)
309 :ivar value: current value of control (subclasses may allow a single value,
310 a sequence of values, or either)
311 :ivar bool disabled: disabled state
312 :ivar bool readonly: readonly state
313 :ivar str id: value of id HTML attribute
314
315 """
316
317 def __init__(self, type, name, attrs, index=None):
318 """
319 type: string describing type of control (see the keys of the
320 HTMLForm.type2class dictionary for the allowable values)
321 name: control name
322 attrs: HTML attributes of control's HTML element
323
324 """
325 raise NotImplementedError()
326
327 def add_to_form(self, form):
328 self._form = form
329 form.controls.append(self)
330
331 def fixup(self):
332 pass
333
334 def is_of_kind(self, kind):
335 raise NotImplementedError()
336
337 def clear(self):
338 raise NotImplementedError()
339
340 def __getattr__(self, name):
341 raise NotImplementedError()
342
343 def __setattr__(self, name, value):
344 raise NotImplementedError()
345
346 def pairs(self):
347 """Return list of (key, value) pairs suitable for passing to urlencode.
348 """
349 return [(k, v) for (i, k, v) in self._totally_ordered_pairs()]
350
351 def _totally_ordered_pairs(self):
352 """Return list of (key, value, index) tuples.
353
354 Like pairs, but allows preserving correct ordering even where several
355 controls are involved.
356
357 """
358 raise NotImplementedError()
359
360 def _write_mime_data(self, mw, name, value):
361 """Write data for a subitem of this control to a MimeWriter."""
362 # called by HTMLForm
363 mw2 = mw.nextpart()
364 mw2.addheader(
365 "Content-Disposition", 'form-data; name="%s"' % as_unicode(name),
366 1)
367 f = mw2.startbody(prefix=0)
368 f.write(value)
369
370 def __str__(self):
371 raise NotImplementedError()
372
373 def get_labels(self):
374 """Return all labels (Label instances) for this control.
375
376 If the control was surrounded by a <label> tag, that will be the first
377 label; all other labels, connected by 'for' and 'id', are in the order
378 that appear in the HTML.
379
380 """
381 res = []
382 if self._label:
383 res.append(self._label)
384 if self.id:
385 res.extend(self._form._id_to_labels.get(self.id, ()))
386 return res
387
388
389 # ---------------------------------------------------
390 class ScalarControl(Control):
391 """Control whose value is not restricted to one of a prescribed set.
392
393 Some ScalarControls don't accept any value attribute. Otherwise, takes a
394 single value, which must be string-like.
395
396 Additional read-only public attribute:
397
398 :ivar dict attrs: dictionary mapping the names of original HTML attributes
399 of the control to their values
400
401 """
402
403 def __init__(self, type, name, attrs, index=None):
404 self._index = index
405 self._label = _get_label(attrs)
406 self.__dict__["type"] = type.lower()
407 self.__dict__["name"] = name
408 self._value = attrs.get("value")
409 self.disabled = 'disabled' in attrs
410 self.readonly = 'readonly' in attrs
411 self.id = attrs.get("id")
412
413 self.attrs = dict(attrs)
414
415 self._clicked = False
416
417 self._urlparse = urlparse
418 self._urlunparse = urlunparse
419
420 def __getattr__(self, name):
421 if name == "value":
422 return self.__dict__["_value"]
423 else:
424 raise AttributeError("%s instance has no attribute '%s'" %
425 (self.__class__.__name__, name))
426
427 def __setattr__(self, name, value):
428 if name == "value":
429 if not isstringlike(value):
430 raise TypeError("must assign a string")
431 elif self.readonly:
432 raise AttributeError("control '%s' is readonly" % self.name)
433 elif self.disabled:
434 raise AttributeError("control '%s' is disabled" % self.name)
435 self.__dict__["_value"] = value
436 elif name in ("name", "type"):
437 raise AttributeError("%s attribute is readonly" % name)
438 else:
439 self.__dict__[name] = value
440
441 def _totally_ordered_pairs(self):
442 name = self.name
443 value = self.value
444 if name is None or value is None or self.disabled:
445 return []
446 return [(self._index, name, value)]
447
448 def clear(self):
449 if self.readonly:
450 raise AttributeError("control '%s' is readonly" % self.name)
451 self.__dict__["_value"] = None
452
453 def __str__(self):
454 name = self.name
455 value = self.value
456 if name is None:
457 name = "<None>"
458 if value is None:
459 value = "<None>"
460
461 infos = []
462 if self.disabled:
463 infos.append("disabled")
464 if self.readonly:
465 infos.append("readonly")
466 info = ", ".join(infos)
467 if info:
468 info = " (%s)" % info
469
470 return "<%s(%s=%s)%s>" % (self.__class__.__name__, name, value, info)
471
472
473 # ---------------------------------------------------
474 class TextControl(ScalarControl):
475 """Textual input control.
476
477 Covers HTML elements: INPUT/TEXT, INPUT/PASSWORD, INPUT/HIDDEN, TEXTAREA
478
479 """
480
481 def __init__(self, type, name, attrs, index=None):
482 ScalarControl.__init__(self, type, name, attrs, index)
483 if self.type == "hidden":
484 self.readonly = True
485 if self._value is None:
486 self._value = ""
487
488 def is_of_kind(self, kind):
489 return kind == "text"
490
491
492 # ---------------------------------------------------
493 class FileControl(ScalarControl):
494 """File upload with INPUT TYPE=FILE.
495
496 The value attribute of a FileControl is always None. Use add_file instead.
497
498 Additional public method: :meth:`add_file`
499
500 """
501
502 def __init__(self, type, name, attrs, index=None):
503 ScalarControl.__init__(self, type, name, attrs, index)
504 self._value = None
505 self._upload_data = []
506
507 def is_of_kind(self, kind):
508 return kind == "file"
509
510 def clear(self):
511 if self.readonly:
512 raise AttributeError("control '%s' is readonly" % self.name)
513 self._upload_data = []
514
515 def __setattr__(self, name, value):
516 if name in ("value", "name", "type"):
517 raise AttributeError("%s attribute is readonly" % name)
518 else:
519 self.__dict__[name] = value
520
521 def add_file(self, file_object, content_type=None, filename=None):
522 ''' Add data from the specified file to be uploaded. content_type and
523 filename are sent in the HTTP headers if specified. '''
524 if not hasattr(file_object, "read"):
525 raise TypeError("file-like object must have read method")
526 if content_type is not None and not isstringlike(content_type):
527 raise TypeError("content type must be None or string-like")
528 if filename is not None and not isstringlike(filename):
529 raise TypeError("filename must be None or string-like")
530 if content_type is None:
531 if getattr(file_object, 'name', None):
532 content_type = guess_type(file_object.name)[0]
533 content_type = content_type or "application/octet-stream"
534 self._upload_data.append((file_object, content_type, filename))
535
536 def _totally_ordered_pairs(self):
537 # XXX should it be successful even if unnamed?
538 if self.name is None or self.disabled:
539 return []
540 return [(self._index, self.name, "")]
541
542 # If enctype is application/x-www-form-urlencoded and there's a FILE
543 # control present, what should be sent? Strictly, it should be 'name=data'
544 # (see HTML 4.01 spec., section 17.13.2), but code sends "name=" ATM. What
545 # about multiple file upload?
546 def _write_mime_data(self, mw, _name, _value):
547 # called by HTMLForm
548 # assert _name == self.name and _value == ''
549 if len(self._upload_data) < 2:
550 if len(self._upload_data) == 0:
551 file_object = BytesIO()
552 content_type = "application/octet-stream"
553 filename = ""
554 else:
555 file_object, content_type, filename = self._upload_data[0]
556 if filename is None:
557 filename = ""
558 mw2 = mw.nextpart()
559 fn_part = '; filename="%s"' % filename
560 disp = 'form-data; name="%s"%s' % (self.name, fn_part)
561 mw2.addheader("Content-Disposition", disp, prefix=1)
562 fh = mw2.startbody(content_type, prefix=0)
563 fh.write(file_object.read())
564 else:
565 # multiple files
566 mw2 = mw.nextpart()
567 disp = 'form-data; name="%s"' % self.name
568 mw2.addheader("Content-Disposition", disp, prefix=1)
569 fh = mw2.startmultipartbody("mixed", prefix=0)
570 for file_object, content_type, filename in self._upload_data:
571 mw3 = mw2.nextpart()
572 if filename is None:
573 filename = ""
574 fn_part = '; filename="%s"' % filename
575 disp = "file%s" % fn_part
576 mw3.addheader("Content-Disposition", disp, prefix=1)
577 fh2 = mw3.startbody(content_type, prefix=0)
578 fh2.write(file_object.read())
579 mw2.lastpart()
580
581 def __str__(self):
582 name = self.name
583 if name is None:
584 name = "<None>"
585
586 if not self._upload_data:
587 value = "<No files added>"
588 else:
589 value = []
590 for file, ctype, filename in self._upload_data:
591 if filename is None:
592 value.append("<Unnamed file>")
593 else:
594 value.append(filename)
595 value = ", ".join(value)
596
597 info = []
598 if self.disabled:
599 info.append("disabled")
600 if self.readonly:
601 info.append("readonly")
602 info = ", ".join(info)
603 if info:
604 info = " (%s)" % info
605
606 return "<%s(%s=%s)%s>" % (self.__class__.__name__, name, value, info)
607
608
609 # ---------------------------------------------------
610 # ---------------------------------------------------
611 class IgnoreControl(ScalarControl):
612 """Control that we're not interested in.
613
614 Covers html elements: INPUT/RESET, BUTTON/RESET, INPUT/BUTTON,
615 BUTTON/BUTTON
616
617 These controls are always unsuccessful, in the terminology of HTML 4 (ie.
618 they never require any information to be returned to the server).
619
620 BUTTON/BUTTON is used to generate events for script embedded in HTML.
621
622 The value attribute of IgnoreControl is always None.
623
624 """
625
626 def __init__(self, type, name, attrs, index=None):
627 ScalarControl.__init__(self, type, name, attrs, index)
628 self._value = None
629
630 def is_of_kind(self, kind):
631 return False
632
633 def __setattr__(self, name, value):
634 if name == "value":
635 raise AttributeError("control '%s' is ignored, hence read-only" %
636 self.name)
637 elif name in ("name", "type"):
638 raise AttributeError("%s attribute is readonly" % name)
639 else:
640 self.__dict__[name] = value
641
642
643 # ---------------------------------------------------
644 # ListControls
645
646 # helpers and subsidiary classes
647
648
649 class Item:
650 def __init__(self, control, attrs, index=None):
651 label = _get_label(attrs)
652 self.__dict__.update({
653 "name": attrs["value"],
654 "_labels": label and [label] or [],
655 "attrs": attrs,
656 "_control": control,
657 "disabled": 'disabled' in attrs,
658 "_selected": False,
659 "id": attrs.get("id"),
660 "_index": index,
661 })
662 control.items.append(self)
663
664 def get_labels(self):
665 """Return all labels (Label instances) for this item.
666
667 For items that represent radio buttons or checkboxes, if the item was
668 surrounded by a <label> tag, that will be the first label; all other
669 labels, connected by 'for' and 'id', are in the order that appear in
670 the HTML.
671
672 For items that represent select options, if the option had a label
673 attribute, that will be the first label. If the option has contents
674 (text within the option tags) and it is not the same as the label
675 attribute (if any), that will be a label. There is nothing in the
676 spec to my knowledge that makes an option with an id unable to be the
677 target of a label's for attribute, so those are included, if any, for
678 the sake of consistency and completeness.
679
680 """
681 res = []
682 res.extend(self._labels)
683 if self.id:
684 res.extend(self._control._form._id_to_labels.get(self.id, ()))
685 return res
686
687 def __getattr__(self, name):
688 if name == "selected":
689 return self._selected
690 raise AttributeError(name)
691
692 def __setattr__(self, name, value):
693 if name == "selected":
694 self._control._set_selected_state(self, value)
695 elif name == "disabled":
696 self.__dict__["disabled"] = bool(value)
697 else:
698 raise AttributeError(name)
699
700 def __str__(self):
701 res = self.name
702 if self.selected:
703 res = "*" + res
704 if self.disabled:
705 res = "(%s)" % res
706 return res
707
708 def __repr__(self):
709 # XXX appending the attrs without distinguishing them from name and id
710 # is silly
711 attrs = [("name", self.name), ("id", self.id)] + list(
712 iteritems(self.attrs))
713 return "<%s %s>" % (self.__class__.__name__,
714 " ".join(["%s=%r" % (k, v) for k, v in attrs]))
715
716
717 def disambiguate(items, nr, **kwds):
718 msgs = []
719 for key, value in iteritems(kwds):
720 msgs.append("%s=%r" % (key, value))
721 msg = " ".join(msgs)
722 if not items:
723 raise ItemNotFoundError(msg)
724 if nr is None:
725 if len(items) > 1:
726 raise AmbiguityError(msg)
727 nr = 0
728 if len(items) <= nr:
729 raise ItemNotFoundError(msg)
730 return items[nr]
731
732
733 class ListControl(Control):
734 """Control representing a sequence of items.
735
736 The value attribute of a ListControl represents the successful list items
737 in the control. The successful list items are those that are selected and
738 not disabled.
739
740 ListControl implements both list controls that take a length-1 value
741 (single-selection) and those that take length >1 values
742 (multiple-selection).
743
744 ListControls accept sequence values only. Some controls only accept
745 sequences of length 0 or 1 (RADIO, and single-selection SELECT).
746 In those cases, ItemCountError is raised if len(sequence) > 1. CHECKBOXes
747 and multiple-selection SELECTs (those having the "multiple" HTML attribute)
748 accept sequences of any length.
749
750 Note the following mistake:
751
752 .. code-block:: python
753
754 control.value = some_value
755 assert control.value == some_value # not necessarily true
756
757 The reason for this is that the value attribute always gives the list items
758 in the order they were listed in the HTML.
759
760 ListControl items can also be referred to by their labels instead of names.
761 Use the label argument to .get(), and the .set_value_by_label(),
762 .get_value_by_label() methods.
763
764 Note that, rather confusingly, though SELECT controls are represented in
765 HTML by SELECT elements (which contain OPTION elements, representing
766 individual list items), CHECKBOXes and RADIOs are not represented by *any*
767 element. Instead, those controls are represented by a collection of INPUT
768 elements. For example, this is a SELECT control, named "control1"::
769
770 <select name="control1">
771 <option>foo</option>
772 <option value="1">bar</option>
773 </select>
774
775 and this is a CHECKBOX control, named "control2"::
776
777 <input type="checkbox" name="control2" value="foo" id="cbe1">
778 <input type="checkbox" name="control2" value="bar" id="cbe2">
779
780 The id attribute of a CHECKBOX or RADIO ListControl is always that of its
781 first element (for example, "cbe1" above).
782
783
784 Additional read-only public attribute: multiple.
785
786 """
787
788 # ListControls are built up by the parser from their component items by
789 # creating one ListControl per item, consolidating them into a single
790 # master ListControl held by the HTMLForm:
791
792 # -User calls form.new_control(...)
793 # -Form creates Control, and calls control.add_to_form(self).
794 # -Control looks for a Control with the same name and type in the form,
795 # and if it finds one, merges itself with that control by calling
796 # control.merge_control(self). The first Control added to the form, of
797 # a particular name and type, is the only one that survives in the
798 # form.
799 # -Form calls control.fixup for all its controls. ListControls in the
800 # form know they can now safely pick their default values.
801
802 # To create a ListControl without an HTMLForm, use:
803
804 # control.merge_control(new_control)
805
806 # (actually, it's much easier just to use ParseFile)
807
808 _label = None
809
810 def __init__(self,
811 type,
812 name,
813 attrs={},
814 select_default=False,
815 called_as_base_class=False,
816 index=None):
817 """
818 select_default: for RADIO and multiple-selection SELECT controls, pick
819 the first item as the default if no 'selected' HTML attribute is
820 present
821
822 """
823 if not called_as_base_class:
824 raise NotImplementedError()
825
826 self.__dict__["type"] = type.lower()
827 self.__dict__["name"] = name
828 self._value = attrs.get("value")
829 self.disabled = False
830 self.readonly = False
831 self.id = attrs.get("id")
832 self._closed = False
833
834 # As Controls are merged in with .merge_control(), self.attrs will
835 # refer to each Control in turn -- always the most recently merged
836 # control. Each merged-in Control instance corresponds to a single
837 # list item: see ListControl.__doc__.:
838 self.items = []
839 self._form = None
840
841 self._select_default = select_default
842 self._clicked = False
843
844 def clear(self):
845 self.value = []
846
847 def is_of_kind(self, kind):
848 if kind == "list":
849 return True
850 elif kind == "multilist":
851 return bool(self.multiple)
852 elif kind == "singlelist":
853 return not self.multiple
854 else:
855 return False
856
857 def get_items(self, name=None, label=None, id=None,
858 exclude_disabled=False):
859 """Return matching items by name or label.
860
861 For argument docs, see the docstring for .get()
862
863 """
864 if name is not None and not isstringlike(name):
865 raise TypeError("item name must be string-like")
866 if label is not None and not isstringlike(label):
867 raise TypeError("item label must be string-like")
868 if id is not None and not isstringlike(id):
869 raise TypeError("item id must be string-like")
870 items = [] # order is important
871 for o in self.items:
872 if exclude_disabled and o.disabled:
873 continue
874 if name is not None and o.name != name:
875 continue
876 if label is not None:
877 for l in o.get_labels():
878 if label in l.text:
879 break
880 else:
881 continue
882 if id is not None and o.id != id:
883 continue
884 items.append(o)
885 return items
886
887 def get(self,
888 name=None,
889 label=None,
890 id=None,
891 nr=None,
892 exclude_disabled=False):
893 """Return item by name or label, disambiguating if necessary with nr.
894
895 All arguments must be passed by name, with the exception of 'name',
896 which may be used as a positional argument.
897
898 If name is specified, then the item must have the indicated name.
899
900 If label is specified, then the item must have a label whose
901 whitespace-compressed, stripped, text substring-matches the indicated
902 label string (e.g. label="please choose" will match
903 " Do please choose an item ").
904
905 If id is specified, then the item must have the indicated id.
906
907 nr is an optional 0-based index of the items matching the query.
908
909 If nr is the default None value and more than item is found, raises
910 AmbiguityError.
911
912 If no item is found, or if items are found but nr is specified and not
913 found, raises ItemNotFoundError.
914
915 Optionally excludes disabled items.
916
917 """
918 items = self.get_items(name, label, id, exclude_disabled)
919 return disambiguate(items, nr, name=name, label=label, id=id)
920
921 def _get(self, name, by_label=False, nr=None, exclude_disabled=False):
922 # strictly for use by deprecated methods
923 if by_label:
924 name, label = None, name
925 else:
926 name, label = name, None
927 return self.get(name, label, nr, exclude_disabled)
928
929 def toggle(self, name, by_label=False, nr=None):
930 """Deprecated: given a name or label and optional disambiguating index
931 nr, toggle the matching item's selection.
932
933 Selecting items follows the behavior described in the docstring of the
934 'get' method.
935
936 if the item is disabled, or this control is disabled or readonly,
937 raise AttributeError.
938
939 """
940 deprecation(
941 "item = control.get(...); item.selected = not item.selected")
942 o = self._get(name, by_label, nr)
943 self._set_selected_state(o, not o.selected)
944
945 def set(self, selected, name, by_label=False, nr=None):
946 """Deprecated: given a name or label and optional disambiguating index
947 nr, set the matching item's selection to the bool value of selected.
948
949 Selecting items follows the behavior described in the docstring of the
950 'get' method.
951
952 if the item is disabled, or this control is disabled or readonly,
953 raise AttributeError.
954
955 """
956 deprecation("control.get(...).selected = <boolean>")
957 self._set_selected_state(self._get(name, by_label, nr), selected)
958
959 def _set_selected_state(self, item, action):
960 # action:
961 # bool False: off
962 # bool True: on
963 if self.disabled:
964 raise AttributeError("control '%s' is disabled" % self.name)
965 if self.readonly:
966 raise AttributeError("control '%s' is readonly" % self.name)
967 action == bool(action)
968 if item.disabled:
969 raise AttributeError("item is disabled")
970 if self.multiple:
971 item.__dict__["_selected"] = action
972 else:
973 if not action:
974 item.__dict__["_selected"] = False
975 else:
976 for o in self.items:
977 o.__dict__["_selected"] = False
978 item.__dict__["_selected"] = True
979
980 def toggle_single(self, by_label=None):
981 """Deprecated: toggle the selection of the single item in this control.
982
983 Raises ItemCountError if the control does not contain only one item.
984
985 by_label argument is ignored, and included only for backwards
986 compatibility.
987
988 """
989 deprecation(
990 "control.items[0].selected = not control.items[0].selected")
991 if len(self.items) != 1:
992 raise ItemCountError("'%s' is not a single-item control" %
993 self.name)
994 item = self.items[0]
995 self._set_selected_state(item, not item.selected)
996
997 def set_single(self, selected, by_label=None):
998 """Deprecated: set the selection of the single item in this control.
999
1000 Raises ItemCountError if the control does not contain only one item.
1001
1002 by_label argument is ignored, and included only for backwards
1003 compatibility.
1004
1005 """
1006 deprecation("control.items[0].selected = <boolean>")
1007 if len(self.items) != 1:
1008 raise ItemCountError("'%s' is not a single-item control" %
1009 self.name)
1010 self._set_selected_state(self.items[0], selected)
1011
1012 def get_item_disabled(self, name, by_label=False, nr=None):
1013 """Get disabled state of named list item in a ListControl."""
1014 deprecation("control.get(...).disabled")
1015 return self._get(name, by_label, nr).disabled
1016
1017 def set_item_disabled(self, disabled, name, by_label=False, nr=None):
1018 """Set disabled state of named list item in a ListControl.
1019
1020 :arg disabled: boolean disabled state
1021
1022 """
1023 deprecation("control.get(...).disabled = <boolean>")
1024 self._get(name, by_label, nr).disabled = disabled
1025
1026 def set_all_items_disabled(self, disabled):
1027 """Set disabled state of all list items in a ListControl.
1028
1029 :arg disabled: boolean disabled state
1030
1031 """
1032 for o in self.items:
1033 o.disabled = disabled
1034
1035 def get_item_attrs(self, name, by_label=False, nr=None):
1036 """Return dictionary of HTML attributes for a single ListControl item.
1037
1038 The HTML element types that describe list items are: OPTION for SELECT
1039 controls, INPUT for the rest. These elements have HTML attributes that
1040 you may occasionally want to know about -- for example, the "alt" HTML
1041 attribute gives a text string describing the item (graphical browsers
1042 usually display this as a tooltip).
1043
1044 The returned dictionary maps HTML attribute names to values. The names
1045 and values are taken from the original HTML.
1046
1047 """
1048 deprecation("control.get(...).attrs")
1049 return self._get(name, by_label, nr).attrs
1050
1051 def close_control(self):
1052 self._closed = True
1053
1054 def add_to_form(self, form):
1055 assert self._form is None or form == self._form, (
1056 "can't add control to more than one form")
1057 self._form = form
1058 if self.name is None:
1059 # always count nameless elements as separate controls
1060 Control.add_to_form(self, form)
1061 else:
1062 for ii in range(len(form.controls) - 1, -1, -1):
1063 control = form.controls[ii]
1064 if control.name == self.name and control.type == self.type:
1065 if control._closed:
1066 Control.add_to_form(self, form)
1067 else:
1068 control.merge_control(self)
1069 break
1070 else:
1071 Control.add_to_form(self, form)
1072
1073 def merge_control(self, control):
1074 assert bool(control.multiple) == bool(self.multiple)
1075 # usually, isinstance(control, self.__class__)
1076 self.items.extend(control.items)
1077
1078 def fixup(self):
1079 """
1080 ListControls are built up from component list items (which are also
1081 ListControls) during parsing. This method should be called after all
1082 items have been added. See :class:`mechanize.ListControl` for the
1083 reason this is required.
1084
1085 """
1086 # Need to set default selection where no item was indicated as being
1087 # selected by the HTML:
1088
1089 # CHECKBOX:
1090 # Nothing should be selected.
1091 # SELECT/single, SELECT/multiple and RADIO:
1092 # RFC 1866 (HTML 2.0): says first item should be selected.
1093 # W3C HTML 4.01 Specification: says that client behaviour is
1094 # undefined in this case. For RADIO, exactly one must be selected,
1095 # though which one is undefined.
1096 # Both Netscape and Microsoft Internet Explorer (IE) choose first
1097 # item for SELECT/single. However, both IE5 and Mozilla (both 1.0
1098 # and Firebird 0.6) leave all items unselected for RADIO and
1099 # SELECT/multiple.
1100
1101 # Since both Netscape and IE all choose the first item for
1102 # SELECT/single, we do the same. OTOH, both Netscape and IE
1103 # leave SELECT/multiple with nothing selected, in violation of RFC 1866
1104 # (but not in violation of the W3C HTML 4 standard); the same is true
1105 # of RADIO (which *is* in violation of the HTML 4 standard). We follow
1106 # RFC 1866 if the _select_default attribute is set, and Netscape and IE
1107 # otherwise. RFC 1866 and HTML 4 are always violated insofar as you
1108 # can deselect all items in a RadioControl.
1109
1110 for o in self.items:
1111 # set items' controls to self, now that we've merged
1112 o.__dict__["_control"] = self
1113
1114 def __getattr__(self, name):
1115 if name == "value":
1116 if self.name is None:
1117 return []
1118 return [
1119 o.name for o in self.items if o.selected and (not o.disabled)
1120 ]
1121 else:
1122 raise AttributeError("%s instance has no attribute '%s'" %
1123 (self.__class__.__name__, name))
1124
1125 def __setattr__(self, name, value):
1126 if name == "value":
1127 if self.disabled:
1128 raise AttributeError("control '%s' is disabled" % self.name)
1129 if self.readonly:
1130 raise AttributeError("control '%s' is readonly" % self.name)
1131 self._set_value(value)
1132 elif name in ("name", "type", "multiple"):
1133 raise AttributeError("%s attribute is readonly" % name)
1134 else:
1135 self.__dict__[name] = value
1136
1137 def _set_value(self, value):
1138 if value is None or isstringlike(value):
1139 raise TypeError("ListControl, must set a sequence")
1140 if not value:
1141 for o in self.items:
1142 if not o.disabled:
1143 o.selected = False
1144 elif self.multiple:
1145 self._multiple_set_value(value)
1146 elif len(value) > 1:
1147 raise ItemCountError("single selection list, must set sequence of "
1148 "length 0 or 1")
1149 else:
1150 self._single_set_value(value)
1151
1152 def _get_items(self, name, target=1):
1153 all_items = self.get_items(name)
1154 items = [o for o in all_items if not o.disabled]
1155 if len(items) < target:
1156 if len(all_items) < target:
1157 raise ItemNotFoundError("insufficient items with name %r" %
1158 name)
1159 else:
1160 raise AttributeError(
1161 "insufficient non-disabled items with name %s" % name)
1162 on = []
1163 off = []
1164 for o in items:
1165 if o.selected:
1166 on.append(o)
1167 else:
1168 off.append(o)
1169 return on, off
1170
1171 def _single_set_value(self, value):
1172 assert len(value) == 1
1173 on, off = self._get_items(value[0])
1174 assert len(on) <= 1
1175 if not on:
1176 off[0].selected = True
1177
1178 def _multiple_set_value(self, value):
1179 turn_on = [] # transactional-ish
1180 turn_off = [
1181 item for item in self.items
1182 if item.selected and (not item.disabled)
1183 ]
1184 names = {}
1185 for nn in value:
1186 names[nn] = names.setdefault(nn, 0) + 1
1187 for name, count in iteritems(names):
1188 on, off = self._get_items(name, count)
1189 for i in range(count):
1190 if on:
1191 item = on[0]
1192 del on[0]
1193 del turn_off[turn_off.index(item)]
1194 else:
1195 item = off[0]
1196 del off[0]
1197 turn_on.append(item)
1198 for item in turn_off:
1199 item.selected = False
1200 for item in turn_on:
1201 item.selected = True
1202
1203 def set_value_by_label(self, value):
1204 """Set the value of control by item labels.
1205
1206 value is expected to be an iterable of strings that are substrings of
1207 the item labels that should be selected. Before substring matching is
1208 performed, the original label text is whitespace-compressed
1209 (consecutive whitespace characters are converted to a single space
1210 character) and leading and trailing whitespace is stripped. Ambiguous
1211 labels: it will not complain as long as all ambiguous labels share the
1212 same item name (e.g. OPTION value).
1213
1214 """
1215 if isstringlike(value):
1216 raise TypeError(value)
1217 if not self.multiple and len(value) > 1:
1218 raise ItemCountError("single selection list, must set sequence of "
1219 "length 0 or 1")
1220 items = []
1221 for nn in value:
1222 found = self.get_items(label=nn)
1223 if len(found) > 1:
1224 # ambiguous labels are fine as long as item names (e.g.
1225 # OPTION values) are same
1226 opt_name = found[0].name
1227 if [o for o in found[1:] if o.name != opt_name]:
1228 raise AmbiguityError(nn)
1229 for o in found:
1230 # For the multiple-item case, we could try to be smarter,
1231 # saving them up and trying to resolve, but that's too much.
1232 if o not in items:
1233 items.append(o)
1234 break
1235 else: # all of them are used
1236 raise ItemNotFoundError(nn)
1237 # now we have all the items that should be on
1238 # let's just turn everything off and then back on.
1239 self.value = []
1240 for o in items:
1241 o.selected = True
1242
1243 def get_value_by_label(self):
1244 """Return the value of the control as given by normalized labels."""
1245 res = []
1246 for o in self.items:
1247 if (not o.disabled) and o.selected:
1248 for l in o.get_labels():
1249 if l.text:
1250 res.append(l.text)
1251 break
1252 else:
1253 res.append(None)
1254 return res
1255
1256 def possible_items(self, by_label=False):
1257 """Deprecated: return the names or labels of all possible items.
1258
1259 Includes disabled items, which may be misleading for some use cases.
1260
1261 """
1262 deprecation("[item.name for item in self.items]")
1263 if by_label:
1264 res = []
1265 for o in self.items:
1266 for l in o.get_labels():
1267 if l.text:
1268 res.append(l.text)
1269 break
1270 else:
1271 res.append(None)
1272 return res
1273 return [o.name for o in self.items]
1274
1275 def _totally_ordered_pairs(self):
1276 if self.disabled or self.name is None:
1277 return []
1278 else:
1279 return [(o._index, self.name, o.name) for o in self.items
1280 if o.selected and not o.disabled]
1281
1282 def __str__(self):
1283 name = self.name
1284 if name is None:
1285 name = "<None>"
1286
1287 display = [str(o) for o in self.items]
1288
1289 infos = []
1290 if self.disabled:
1291 infos.append("disabled")
1292 if self.readonly:
1293 infos.append("readonly")
1294 info = ", ".join(infos)
1295 if info:
1296 info = " (%s)" % info
1297
1298 return "<%s(%s=[%s])%s>" % (self.__class__.__name__, name,
1299 ", ".join(display), info)
1300
1301
1302 class RadioControl(ListControl):
1303 """
1304 Covers:
1305
1306 INPUT/RADIO
1307
1308 """
1309
1310 def __init__(self, type, name, attrs, select_default=False, index=None):
1311 attrs.setdefault("value", "on")
1312 ListControl.__init__(
1313 self,
1314 type,
1315 name,
1316 attrs,
1317 select_default,
1318 called_as_base_class=True,
1319 index=index)
1320 self.__dict__["multiple"] = False
1321 o = Item(self, attrs, index)
1322 o.__dict__["_selected"] = 'checked' in attrs
1323
1324 def fixup(self):
1325 ListControl.fixup(self)
1326 found = [o for o in self.items if o.selected and not o.disabled]
1327 if not found:
1328 if self._select_default:
1329 for o in self.items:
1330 if not o.disabled:
1331 o.selected = True
1332 break
1333 else:
1334 # Ensure only one item selected. Choose the last one,
1335 # following IE and Firefox.
1336 for o in found[:-1]:
1337 o.selected = False
1338
1339 def get_labels(self):
1340 return []
1341
1342
1343 class CheckboxControl(ListControl):
1344 """
1345 Covers:
1346
1347 INPUT/CHECKBOX
1348
1349 """
1350
1351 def __init__(self, type, name, attrs, select_default=False, index=None):
1352 attrs.setdefault("value", "on")
1353 ListControl.__init__(
1354 self,
1355 type,
1356 name,
1357 attrs,
1358 select_default,
1359 called_as_base_class=True,
1360 index=index)
1361 self.__dict__["multiple"] = True
1362 o = Item(self, attrs, index)
1363 o.__dict__["_selected"] = 'checked' in attrs
1364
1365 def get_labels(self):
1366 return []
1367
1368
1369 class SelectControl(ListControl):
1370 """
1371 Covers:
1372
1373 SELECT (and OPTION)
1374
1375
1376 OPTION 'values', in HTML parlance, are Item 'names' in mechanize parlance.
1377
1378 SELECT control values and labels are subject to some messy defaulting
1379 rules. For example, if the HTML representation of the control is::
1380
1381 <SELECT name=year>
1382 <OPTION value=0 label="2002">current year</OPTION>
1383 <OPTION value=1>2001</OPTION>
1384 <OPTION>2000</OPTION>
1385 </SELECT>
1386
1387 The items, in order, have labels "2002", "2001" and "2000", whereas their
1388 names (the OPTION values) are "0", "1" and "2000" respectively. Note that
1389 the value of the last OPTION in this example defaults to its contents, as
1390 specified by RFC 1866, as do the labels of the second and third OPTIONs.
1391
1392 The OPTION labels are sometimes more meaningful than the OPTION values,
1393 which can make for more maintainable code.
1394
1395 Additional read-only public attribute: attrs
1396
1397 The attrs attribute is a dictionary of the original HTML attributes of the
1398 SELECT element. Other ListControls do not have this attribute, because in
1399 other cases the control as a whole does not correspond to any single HTML
1400 element. control.get(...).attrs may be used as usual to get at the HTML
1401 attributes of the HTML elements corresponding to individual list items (for
1402 SELECT controls, these are OPTION elements).
1403
1404 Another special case is that the Item.attrs dictionaries have a special key
1405 "contents" which does not correspond to any real HTML attribute, but rather
1406 contains the contents of the OPTION element::
1407
1408 <OPTION>this bit</OPTION>
1409
1410 """
1411
1412 # HTML attributes here are treated slightly differently from other list
1413 # controls:
1414 # -The SELECT HTML attributes dictionary is stuffed into the OPTION
1415 # HTML attributes dictionary under the "__select" key.
1416 # -The content of each OPTION element is stored under the special
1417 # "contents" key of the dictionary.
1418 # After all this, the dictionary is passed to the SelectControl constructor
1419 # as the attrs argument, as usual. However:
1420 # -The first SelectControl constructed when building up a SELECT control
1421 # has a constructor attrs argument containing only the __select key -- so
1422 # this SelectControl represents an empty SELECT control.
1423 # -Subsequent SelectControls have both OPTION HTML-attribute in attrs and
1424 # the __select dictionary containing the SELECT HTML-attributes.
1425
1426 def __init__(self, type, name, attrs, select_default=False, index=None):
1427 # fish out the SELECT HTML attributes from the OPTION HTML attributes
1428 # dictionary
1429 self.attrs = dict(attrs["__select"])
1430 self.__dict__["_label"] = _get_label(self.attrs)
1431 self.__dict__["id"] = self.attrs.get("id")
1432 self.__dict__["multiple"] = 'multiple' in self.attrs
1433 # the majority of the contents, label, and value dance already happened
1434 contents = attrs.get("contents")
1435 attrs = dict(attrs)
1436 del attrs["__select"]
1437
1438 ListControl.__init__(
1439 self,
1440 type,
1441 name,
1442 self.attrs,
1443 select_default,
1444 called_as_base_class=True,
1445 index=index)
1446 self.disabled = 'disabled' in self.attrs
1447 self.readonly = 'readonly' in self.attrs
1448 if 'value' in attrs:
1449 # otherwise it is a marker 'select started' token
1450 o = Item(self, attrs, index)
1451 o.__dict__["_selected"] = 'selected' in attrs
1452 # add 'label' label and contents label, if different. If both are
1453 # provided, the 'label' label is used for display in HTML
1454 # 4.0-compliant browsers (and any lower spec? not sure) while the
1455 # contents are used for display in older or less-compliant
1456 # browsers. We make label objects for both, if the values are
1457 # different.
1458 label = attrs.get("label")
1459 if label:
1460 o._labels.append(Label(label))
1461 if contents and contents != label:
1462 o._labels.append(Label(contents))
1463 elif contents:
1464 o._labels.append(Label(contents))
1465
1466 def fixup(self):
1467 ListControl.fixup(self)
1468 # Firefox doesn't exclude disabled items from those considered here
1469 # (i.e. from 'found', for both branches of the if below). Note that
1470 # IE6 doesn't support the disabled attribute on OPTIONs at all.
1471 found = [o for o in self.items if o.selected]
1472 if not found:
1473 if not self.multiple or self._select_default:
1474 for o in self.items:
1475 if not o.disabled:
1476 was_disabled = self.disabled
1477 self.disabled = False
1478 try:
1479 o.selected = True
1480 finally:
1481 o.disabled = was_disabled
1482 break
1483 elif not self.multiple:
1484 # Ensure only one item selected. Choose the last one,
1485 # following IE and Firefox.
1486 for o in found[:-1]:
1487 o.selected = False
1488
1489
1490 # ---------------------------------------------------
1491 class SubmitControl(ScalarControl):
1492 """
1493 Covers:
1494
1495 INPUT/SUBMIT
1496 BUTTON/SUBMIT
1497
1498 """
1499
1500 def __init__(self, type, name, attrs, index=None):
1501 ScalarControl.__init__(self, type, name, attrs, index)
1502 # IE5 defaults SUBMIT value to "Submit Query"; Firebird 0.6 leaves it
1503 # blank, Konqueror 3.1 defaults to "Submit". HTML spec. doesn't seem
1504 # to define this.
1505 if self.value is None:
1506 self.__dict__['_value'] = ""
1507 self.readonly = True
1508
1509 def get_labels(self):
1510 res = []
1511 if self.value:
1512 res.append(Label(self.value))
1513 res.extend(ScalarControl.get_labels(self))
1514 return res
1515
1516 def is_of_kind(self, kind):
1517 return kind == "clickable"
1518
1519 def _click(self, form, coord, return_type, request_class=_request.Request):
1520 self._clicked = coord
1521 r = form._switch_click(return_type, request_class)
1522 self._clicked = False
1523 return r
1524
1525 def _totally_ordered_pairs(self):
1526 if not self._clicked:
1527 return []
1528 return ScalarControl._totally_ordered_pairs(self)
1529
1530
1531 # ---------------------------------------------------
1532 class ImageControl(SubmitControl):
1533 """
1534 Covers:
1535
1536 INPUT/IMAGE
1537
1538 Coordinates are specified using one of the HTMLForm.click* methods.
1539
1540 """
1541
1542 def __init__(self, type, name, attrs, index=None):
1543 SubmitControl.__init__(self, type, name, attrs, index)
1544 self.readonly = False
1545
1546 def _totally_ordered_pairs(self):
1547 clicked = self._clicked
1548 if self.disabled or not clicked:
1549 return []
1550 name = self.name
1551 if name is None:
1552 return []
1553 pairs = [
1554 (self._index, "%s.x" % name, str(clicked[0])),
1555 (self._index + 1, "%s.y" % name, str(clicked[1])),
1556 ]
1557 value = self._value
1558 if value:
1559 pairs.append((self._index + 2, name, value))
1560 return pairs
1561
1562 get_labels = ScalarControl.get_labels
1563
1564
1565 # aliases, just to make str(control) and str(form) clearer
1566 class PasswordControl(TextControl):
1567 pass
1568
1569
1570 class HiddenControl(TextControl):
1571 pass
1572
1573
1574 class TextareaControl(TextControl):
1575 pass
1576
1577
1578 class SubmitButtonControl(SubmitControl):
1579 pass
1580
1581
1582 def is_listcontrol(control):
1583 return control.is_of_kind("list")
1584
1585
1586 class HTMLForm:
1587 """
1588 Represents a single HTML <form> ... </form> element.
1589
1590 A form consists of a sequence of controls that usually have names, and
1591 which can take on various values. The values of the various types of
1592 controls represent variously: text, zero-or-one-of-many or many-of-many
1593 choices, and files to be uploaded. Some controls can be clicked on to
1594 submit the form, and clickable controls' values sometimes include the
1595 coordinates of the click.
1596
1597 Forms can be filled in with data to be returned to the server, and then
1598 submitted, using the click method to generate a request object suitable for
1599 passing to :func:`mechanize.urlopen` (or the click_request_data or
1600 click_pairs methods for integration with third-party code).
1601
1602 Usually, HTMLForm instances are not created directly. Instead, they are
1603 automatically created when visting a page with a mechanize Browser. If you
1604 do construct HTMLForm objects yourself, however, note that an HTMLForm
1605 instance is only properly initialised after the fixup method has been
1606 called. See :class:`mechanize.ListControl` for the reason this is
1607 required.
1608
1609 Indexing a form (form["control_name"]) returns the named Control's value
1610 attribute. Assignment to a form index (form["control_name"] = something)
1611 is equivalent to assignment to the named Control's value attribute. If you
1612 need to be more specific than just supplying the control's name, use the
1613 set_value and get_value methods.
1614
1615 ListControl values are lists of item names (specifically, the names of the
1616 items that are selected and not disabled, and hence are "successful" -- ie.
1617 cause data to be returned to the server). The list item's name is the
1618 value of the corresponding HTML element's"value" attribute.
1619
1620 Example::
1621
1622 <INPUT type="CHECKBOX" name="cheeses" value="leicester"></INPUT>
1623 <INPUT type="CHECKBOX" name="cheeses" value="cheddar"></INPUT>
1624
1625 defines a CHECKBOX control with name "cheeses" which has two items, named
1626 "leicester" and "cheddar".
1627
1628 Another example::
1629
1630 <SELECT name="more_cheeses">
1631 <OPTION>1</OPTION>
1632 <OPTION value="2" label="CHEDDAR">cheddar</OPTION>
1633 </SELECT>
1634
1635 defines a SELECT control with name "more_cheeses" which has two items,
1636 named "1" and "2" (because the OPTION element's value HTML attribute
1637 defaults to the element contents -- see :class:`mechanize.SelectControl`
1638 for more on these defaulting rules).
1639
1640 To select, deselect or otherwise manipulate individual list items, use the
1641 :meth:`mechanize.HTMLForm.find_control()` and
1642 :meth:`mechanize.ListControl.get()` methods. To set the whole value, do as
1643 for any other control: use indexing or the `set_value/get_value` methods.
1644
1645 Example:
1646
1647 .. code-block:: python
1648
1649 # select *only* the item named "cheddar"
1650 form["cheeses"] = ["cheddar"]
1651 # select "cheddar", leave other items unaffected
1652 form.find_control("cheeses").get("cheddar").selected = True
1653
1654 Some controls (RADIO and SELECT without the multiple attribute) can only
1655 have zero or one items selected at a time. Some controls (CHECKBOX and
1656 SELECT with the multiple attribute) can have multiple items selected at a
1657 time. To set the whole value of a ListControl, assign a sequence to a form
1658 index:
1659
1660 .. code-block:: python
1661
1662 form["cheeses"] = ["cheddar", "leicester"]
1663
1664 If the ListControl is not multiple-selection, the assigned list must be of
1665 length one.
1666
1667 To check if a control has an item, if an item is selected, or if an item is
1668 successful (selected and not disabled), respectively:
1669
1670 .. code-block:: python
1671
1672 "cheddar" in [item.name for item in form.find_control("cheeses").items]
1673 "cheddar" in [item.name for item in form.find_control("cheeses").items
1674 and item.selected]
1675 "cheddar" in form["cheeses"]
1676 # or
1677 "cheddar" in form.get_value("cheeses")
1678
1679 Note that some list items may be disabled (see below).
1680
1681 Note the following mistake:
1682
1683 .. code-block:: python
1684
1685 form[control_name] = control_value
1686 assert form[control_name] == control_value # not necessarily true
1687
1688 The reason for this is that form[control_name] always gives the list items
1689 in the order they were listed in the HTML.
1690
1691 List items (hence list values, too) can be referred to in terms of list
1692 item labels rather than list item names using the appropriate label
1693 arguments. Note that each item may have several labels.
1694
1695 The question of default values of OPTION contents, labels and values is
1696 somewhat complicated: see :class:`mechanize.SelectControl` and
1697 :meth:`mechanize.ListControl.get_item_attrs()` if you think you need to
1698 know.
1699
1700 Controls can be disabled or readonly. In either case, the control's value
1701 cannot be changed until you clear those flags (see example below).
1702 Disabled is the state typically represented by browsers by 'greying out' a
1703 control. Disabled controls are not 'successful' -- they don't cause data
1704 to get returned to the server. Readonly controls usually appear in
1705 browsers as read-only text boxes. Readonly controls are successful. List
1706 items can also be disabled. Attempts to select or deselect disabled items
1707 fail with AttributeError.
1708
1709 If a lot of controls are readonly, it can be useful to do this:
1710
1711 .. code-block:: python
1712
1713 form.set_all_readonly(False)
1714
1715 To clear a control's value attribute, so that it is not successful (until a
1716 value is subsequently set):
1717
1718 .. code-block:: python
1719
1720 form.clear("cheeses")
1721
1722 More examples:
1723
1724 .. code-block:: python
1725
1726 control = form.find_control("cheeses")
1727 control.disabled = False
1728 control.readonly = False
1729 control.get("gruyere").disabled = True
1730 control.items[0].selected = True
1731
1732 See the various Control classes for further documentation. Many methods
1733 take name, type, kind, id, label and nr arguments to specify the control to
1734 be operated on: see :meth:`mechanize.HTMLForm.find_control()`.
1735
1736 ControlNotFoundError (subclass of ValueError) is raised if the specified
1737 control can't be found. This includes occasions where a non-ListControl
1738 is found, but the method (set, for example) requires a ListControl.
1739 ItemNotFoundError (subclass of ValueError) is raised if a list item can't
1740 be found. ItemCountError (subclass of ValueError) is raised if an attempt
1741 is made to select more than one item and the control doesn't allow that, or
1742 set/get_single are called and the control contains more than one item.
1743 AttributeError is raised if a control or item is readonly or disabled and
1744 an attempt is made to alter its value.
1745
1746 Security note: Remember that any passwords you store in HTMLForm instances
1747 will be saved to disk in the clear if you pickle them (directly or
1748 indirectly). The simplest solution to this is to avoid pickling HTMLForm
1749 objects. You could also pickle before filling in any password, or just set
1750 the password to "" before pickling.
1751
1752
1753 Public attributes:
1754
1755 :ivar action: full (absolute URI) form action
1756 :ivar method: "GET" or "POST"
1757 :ivar enctype: form transfer encoding MIME type
1758 :ivar name: name of form (None if no name was specified)
1759 :ivar attrs: dictionary mapping original HTML form attributes to their
1760 values
1761 :ivar controls: list of Control instances; do not alter this list
1762 (instead, call form.new_control to make a Control and add it to the
1763 form, or control.add_to_form if you already have a Control instance)
1764
1765
1766
1767 Methods for form filling:
1768
1769 Most of the these methods have very similar arguments. See
1770 :meth:`mechanize.HTMLForm.find_control()` for details of the name, type,
1771 kind, label and nr arguments.
1772
1773 .. code-block:: python
1774
1775 def find_control(self,
1776 name=None, type=None, kind=None, id=None,
1777 predicate=None, nr=None, label=None)
1778
1779 get_value(name=None, type=None, kind=None, id=None, nr=None,
1780 by_label=False, # by_label is deprecated
1781 label=None)
1782 set_value(value,
1783 name=None, type=None, kind=None, id=None, nr=None,
1784 by_label=False, # by_label is deprecated
1785 label=None)
1786
1787 clear_all()
1788 clear(name=None, type=None, kind=None, id=None, nr=None, label=None)
1789
1790 set_all_readonly(readonly)
1791
1792
1793 Method applying only to FileControls:
1794
1795 .. code-block:: python
1796
1797 add_file(file_object,
1798 content_type="application/octet-stream", filename=None,
1799 name=None, id=None, nr=None, label=None)
1800
1801
1802 Methods applying only to clickable controls:
1803
1804 .. code-block:: python
1805
1806 click(name=None, type=None, id=None, nr=0, coord=(1,1), label=None)
1807 click_request_data(name=None, type=None, id=None, nr=0, coord=(1,1),
1808 label=None)
1809 click_pairs(name=None, type=None, id=None, nr=0, coord=(1,1),
1810 label=None)
1811
1812 """
1813
1814 type2class = {
1815 "text": TextControl,
1816 "password": PasswordControl,
1817 "hidden": HiddenControl,
1818 "textarea": TextareaControl,
1819 "file": FileControl,
1820 "button": IgnoreControl,
1821 "buttonbutton": IgnoreControl,
1822 "reset": IgnoreControl,
1823 "resetbutton": IgnoreControl,
1824 "submit": SubmitControl,
1825 "submitbutton": SubmitButtonControl,
1826 "image": ImageControl,
1827 "radio": RadioControl,
1828 "checkbox": CheckboxControl,
1829 "select": SelectControl,
1830 }
1831
1832 # ---------------------------------------------------
1833 # Initialisation. Use ParseResponse / ParseFile instead.
1834
1835 def __init__(self,
1836 action,
1837 method="GET",
1838 enctype="application/x-www-form-urlencoded",
1839 name=None,
1840 attrs=None,
1841 request_class=_request.Request,
1842 forms=None,
1843 labels=None,
1844 id_to_labels=None,
1845 encoding=None):
1846 """
1847 In the usual case, use ParseResponse (or ParseFile) to create new
1848 HTMLForm objects.
1849
1850 action: full (absolute URI) form action
1851 method: "GET" or "POST"
1852 enctype: form transfer encoding MIME type
1853 name: name of form
1854 attrs: dictionary mapping original HTML form attributes to their values
1855
1856 """
1857 self.action = action
1858 self.method = method
1859 self.enctype = enctype
1860 self.form_encoding = encoding or 'utf-8'
1861 self.name = name
1862 if attrs is not None:
1863 self.attrs = dict(attrs)
1864 else:
1865 self.attrs = {}
1866 self.controls = []
1867 self._request_class = request_class
1868
1869 # these attributes are used by zope.testbrowser
1870 self._forms = forms # this is a semi-public API!
1871 self._labels = labels # this is a semi-public API!
1872 self._id_to_labels = id_to_labels # this is a semi-public API!
1873
1874 self._urlunparse = urlunparse
1875 self._urlparse = urlparse
1876
1877 def new_control(self,
1878 type,
1879 name,
1880 attrs,
1881 ignore_unknown=False,
1882 select_default=False,
1883 index=None):
1884 """Adds a new control to the form.
1885
1886 This is usually called by mechanize. Don't call it
1887 yourself unless you're building your own Control instances.
1888
1889 Note that controls representing lists of items are built up from
1890 controls holding only a single list item. See
1891 :class:`mechanize.ListControl` for further information.
1892
1893 :arg type: type of control (see :class:`mechanize.Control` for a list)
1894 :arg attrs: HTML attributes of control
1895 :arg ignore_unknown: if true, use a dummy Control instance for controls
1896 of unknown type; otherwise, use a TextControl
1897 :arg select_default: for RADIO and multiple-selection SELECT controls,
1898 pick the first item as the default if no 'selected' HTML attribute
1899 is present (this defaulting happens when the HTMLForm.fixup method
1900 is called)
1901 :arg index: index of corresponding element in HTML (see
1902 MoreFormTests.test_interspersed_controls for motivation)
1903
1904 """
1905 type = type.lower()
1906 klass = self.type2class.get(type)
1907 if klass is None:
1908 if ignore_unknown:
1909 klass = IgnoreControl
1910 else:
1911 klass = TextControl
1912
1913 a = dict(attrs)
1914 if issubclass(klass, ListControl):
1915 control = klass(type, name, a, select_default, index)
1916 else:
1917 control = klass(type, name, a, index)
1918
1919 if type == "select" and len(attrs) == 1:
1920 for ii in range(len(self.controls) - 1, -1, -1):
1921 ctl = self.controls[ii]
1922 if ctl.type == "select":
1923 ctl.close_control()
1924 break
1925
1926 control.add_to_form(self)
1927 control._urlparse = self._urlparse
1928 control._urlunparse = self._urlunparse
1929
1930 def fixup(self):
1931 """Normalise form after all controls have been added.
1932
1933 This is usually called by ParseFile and ParseResponse. Don't call it
1934 youself unless you're building your own Control instances.
1935
1936 This method should only be called once, after all controls have been
1937 added to the form.
1938
1939 """
1940 for control in self.controls:
1941 control.fixup()
1942 control.form_encoding = self.form_encoding
1943
1944 # ---------------------------------------------------
1945
1946 def __str__(self):
1947 header = "%s%s %s %s" % ((self.name and self.name + " " or ""),
1948 self.method, self.action, self.enctype)
1949 rep = [header]
1950 for control in self.controls:
1951 rep.append(" %s" % str(control))
1952 return "<%s>" % "\n".join(rep)
1953
1954 # ---------------------------------------------------
1955 # Form-filling methods.
1956
1957 def __getitem__(self, name):
1958 return self.find_control(name).value
1959
1960 def __contains__(self, name):
1961 return bool(self.find_control(name))
1962
1963 def __setitem__(self, name, value):
1964 control = self.find_control(name)
1965 try:
1966 control.value = value
1967 except AttributeError as e:
1968 raise ValueError(str(e))
1969
1970 def get_value(
1971 self,
1972 name=None,
1973 type=None,
1974 kind=None,
1975 id=None,
1976 nr=None,
1977 by_label=False, # by_label is deprecated
1978 label=None):
1979 """Return value of control.
1980
1981 If only name and value arguments are supplied, equivalent to
1982
1983 .. code-block:: python
1984
1985 form[name]
1986
1987 """
1988 if by_label:
1989 deprecation("form.get_value_by_label(...)")
1990 c = self.find_control(name, type, kind, id, label=label, nr=nr)
1991 if by_label:
1992 try:
1993 meth = c.get_value_by_label
1994 except AttributeError:
1995 raise NotImplementedError(
1996 "control '%s' does not yet support by_label" % c.name)
1997 else:
1998 return meth()
1999 else:
2000 return c.value
2001
2002 def set_value(
2003 self,
2004 value,
2005 name=None,
2006 type=None,
2007 kind=None,
2008 id=None,
2009 nr=None,
2010 by_label=False, # by_label is deprecated
2011 label=None):
2012 """Set value of control.
2013
2014 If only name and value arguments are supplied, equivalent to
2015
2016 .. code-block:: python
2017
2018 form[name] = value
2019
2020 """
2021 if by_label:
2022 deprecation("form.get_value_by_label(...)")
2023 c = self.find_control(name, type, kind, id, label=label, nr=nr)
2024 if by_label:
2025 try:
2026 meth = c.set_value_by_label
2027 except AttributeError:
2028 raise NotImplementedError(
2029 "control '%s' does not yet support by_label" % c.name)
2030 else:
2031 meth(value)
2032 else:
2033 c.value = value
2034
2035 def get_value_by_label(self,
2036 name=None,
2037 type=None,
2038 kind=None,
2039 id=None,
2040 label=None,
2041 nr=None):
2042 """
2043
2044 All arguments should be passed by name.
2045
2046 """
2047 c = self.find_control(name, type, kind, id, label=label, nr=nr)
2048 return c.get_value_by_label()
2049
2050 def set_value_by_label(self,
2051 value,
2052 name=None,
2053 type=None,
2054 kind=None,
2055 id=None,
2056 label=None,
2057 nr=None):
2058 """
2059
2060 All arguments should be passed by name.
2061
2062 """
2063 c = self.find_control(name, type, kind, id, label=label, nr=nr)
2064 c.set_value_by_label(value)
2065
2066 def set_all_readonly(self, readonly):
2067 for control in self.controls:
2068 control.readonly = bool(readonly)
2069
2070 def clear_all(self):
2071 """Clear the value attributes of all controls in the form.
2072
2073 See :meth:`mechanize.HTMLForm.clear()`
2074
2075 """
2076 for control in self.controls:
2077 control.clear()
2078
2079 def clear(self,
2080 name=None,
2081 type=None,
2082 kind=None,
2083 id=None,
2084 nr=None,
2085 label=None):
2086 """Clear the value attribute of a control.
2087
2088 As a result, the affected control will not be successful until a value
2089 is subsequently set. AttributeError is raised on readonly controls.
2090
2091 """
2092 c = self.find_control(name, type, kind, id, label=label, nr=nr)
2093 c.clear()
2094
2095 # ---------------------------------------------------
2096 # Form-filling methods applying only to ListControls.
2097
2098 def possible_items(
2099 self, # deprecated
2100 name=None,
2101 type=None,
2102 kind=None,
2103 id=None,
2104 nr=None,
2105 by_label=False,
2106 label=None):
2107 """Return a list of all values that the specified control can take."""
2108 c = self._find_list_control(name, type, kind, id, label, nr)
2109 return c.possible_items(by_label)
2110
2111 def set(
2112 self,
2113 selected,
2114 item_name, # deprecated
2115 name=None,
2116 type=None,
2117 kind=None,
2118 id=None,
2119 nr=None,
2120 by_label=False,
2121 label=None):
2122 """Select / deselect named list item.
2123
2124 :arg selected: boolean selected state
2125
2126 """
2127 self._find_list_control(name, type, kind, id, label, nr).set(
2128 selected, item_name, by_label)
2129
2130 def toggle(
2131 self,
2132 item_name, # deprecated
2133 name=None,
2134 type=None,
2135 kind=None,
2136 id=None,
2137 nr=None,
2138 by_label=False,
2139 label=None):
2140 """Toggle selected state of named list item."""
2141 self._find_list_control(name, type, kind, id, label, nr).toggle(
2142 item_name, by_label)
2143
2144 def set_single(
2145 self,
2146 selected, # deprecated
2147 name=None,
2148 type=None,
2149 kind=None,
2150 id=None,
2151 nr=None,
2152 by_label=None,
2153 label=None):
2154 """Select / deselect list item in a control having only one item.
2155
2156 If the control has multiple list items, ItemCountError is raised.
2157
2158 This is just a convenience method, so you don't need to know the item's
2159 name -- the item name in these single-item controls is usually
2160 something meaningless like "1" or "on".
2161
2162 For example, if a checkbox has a single item named "on", the following
2163 two calls are equivalent:
2164
2165 .. code-block:: python
2166
2167 control.toggle("on")
2168 control.toggle_single()
2169
2170 """ # by_label ignored and deprecated
2171 self._find_list_control(name, type, kind, id, label,
2172 nr).set_single(selected)
2173
2174 def toggle_single(self,
2175 name=None,
2176 type=None,
2177 kind=None,
2178 id=None,
2179 nr=None,
2180 by_label=None,
2181 label=None): # deprecated
2182 """Toggle selected state of list item in control having only one item.
2183
2184 The rest is as for :meth:`mechanize.HTMLForm.set_single()`
2185
2186 """ # by_label ignored and deprecated
2187 self._find_list_control(name, type, kind, id, label,
2188 nr).toggle_single()
2189
2190 # ---------------------------------------------------
2191 # Form-filling method applying only to FileControls.
2192
2193 def add_file(self,
2194 file_object,
2195 content_type=None,
2196 filename=None,
2197 name=None,
2198 id=None,
2199 nr=None,
2200 label=None):
2201 """Add a file to be uploaded.
2202
2203 :arg file_object: file-like object (with read method) from which to
2204 read data to upload
2205 :arg content_type: MIME content type of data to upload
2206 :arg filename: filename to pass to server
2207
2208 If filename is None, no filename is sent to the server.
2209
2210 If content_type is None, the content type is guessed based on the
2211 filename and the data from read from the file object.
2212
2213 At the moment, guessed content type is always application/octet-stream.
2214
2215 Note the following useful HTML attributes of file upload controls (see
2216 HTML 4.01 spec, section 17):
2217
2218 * `accept`: comma-separated list of content types
2219 that the server will handle correctly;
2220 you can use this to filter out non-conforming files
2221 * `size`: XXX IIRC, this is indicative of whether form
2222 wants multiple or single files
2223 * `maxlength`: XXX hint of max content length in bytes?
2224
2225 """
2226 self.find_control(
2227 name, "file", id=id, label=label,
2228 nr=nr).add_file(file_object, content_type, filename)
2229
2230 # ---------------------------------------------------
2231 # Form submission methods, applying only to clickable controls.
2232
2233 def click(self,
2234 name=None,
2235 type=None,
2236 id=None,
2237 nr=0,
2238 coord=(1, 1),
2239 request_class=_request.Request,
2240 label=None):
2241 """Return request that would result from clicking on a control.
2242
2243 The request object is a mechanize.Request instance, which you can pass
2244 to mechanize.urlopen.
2245
2246 Only some control types (INPUT/SUBMIT & BUTTON/SUBMIT buttons and
2247 IMAGEs) can be clicked.
2248
2249 Will click on the first clickable control, subject to the name, type
2250 and nr arguments (as for find_control). If no name, type, id or number
2251 is specified and there are no clickable controls, a request will be
2252 returned for the form in its current, un-clicked, state.
2253
2254 IndexError is raised if any of name, type, id or nr is specified but no
2255 matching control is found. ValueError is raised if the HTMLForm has an
2256 enctype attribute that is not recognised.
2257
2258 You can optionally specify a coordinate to click at, which only makes a
2259 difference if you clicked on an image.
2260
2261 """
2262 return self._click(name, type, id, label, nr, coord, "request",
2263 self._request_class)
2264
2265 def click_request_data(self,
2266 name=None,
2267 type=None,
2268 id=None,
2269 nr=0,
2270 coord=(1, 1),
2271 request_class=_request.Request,
2272 label=None):
2273 """As for click method, but return a tuple (url, data, headers).
2274
2275 You can use this data to send a request to the server. This is useful
2276 if you're using httplib or urllib rather than mechanize. Otherwise,
2277 use the click method.
2278
2279 """
2280 return self._click(name, type, id, label, nr, coord, "request_data",
2281 self._request_class)
2282
2283 def click_pairs(self,
2284 name=None,
2285 type=None,
2286 id=None,
2287 nr=0,
2288 coord=(1, 1),
2289 label=None):
2290 """As for click_request_data, but returns a list of (key, value) pairs.
2291
2292 You can use this list as an argument to urllib.urlencode. This is
2293 usually only useful if you're using httplib or urllib rather than
2294 mechanize. It may also be useful if you want to manually tweak the
2295 keys and/or values, but this should not be necessary. Otherwise, use
2296 the click method.
2297
2298 Note that this method is only useful for forms of MIME type
2299 x-www-form-urlencoded. In particular, it does not return the
2300 information required for file upload. If you need file upload and are
2301 not using mechanize, use click_request_data.
2302 """
2303 return self._click(name, type, id, label, nr, coord, "pairs",
2304 self._request_class)
2305
2306 # ---------------------------------------------------
2307
2308 def find_control(self,
2309 name=None,
2310 type=None,
2311 kind=None,
2312 id=None,
2313 predicate=None,
2314 nr=None,
2315 label=None):
2316 """Locate and return some specific control within the form.
2317
2318 At least one of the name, type, kind, predicate and nr arguments must
2319 be supplied. If no matching control is found, ControlNotFoundError is
2320 raised.
2321
2322 If name is specified, then the control must have the indicated name.
2323
2324 If type is specified then the control must have the specified type (in
2325 addition to the types possible for <input> HTML tags: "text",
2326 "password", "hidden", "submit", "image", "button", "radio", "checkbox",
2327 "file" we also have "reset", "buttonbutton", "submitbutton",
2328 "resetbutton", "textarea", "select").
2329
2330 If kind is specified, then the control must fall into the specified
2331 group, each of which satisfies a particular interface. The types are
2332 "text", "list", "multilist", "singlelist", "clickable" and "file".
2333
2334 If id is specified, then the control must have the indicated id.
2335
2336 If predicate is specified, then the control must match that function.
2337 The predicate function is passed the control as its single argument,
2338 and should return a boolean value indicating whether the control
2339 matched.
2340
2341 nr, if supplied, is the sequence number of the control (where 0 is the
2342 first). Note that control 0 is the first control matching all the
2343 other arguments (if supplied); it is not necessarily the first control
2344 in the form. If no nr is supplied, AmbiguityError is raised if
2345 multiple controls match the other arguments.
2346
2347 If label is specified, then the control must have this label. Note
2348 that radio controls and checkboxes never have labels: their items do.
2349
2350 """
2351 if ((name is None) and (type is None) and (kind is None) and
2352 (id is None) and (label is None) and (predicate is None) and
2353 (nr is None)):
2354 raise ValueError(
2355 "at least one argument must be supplied to specify control")
2356 return self._find_control(name, type, kind, id, label, predicate, nr)
2357
2358 # ---------------------------------------------------
2359 # Private methods.
2360
2361 def _find_list_control(self,
2362 name=None,
2363 type=None,
2364 kind=None,
2365 id=None,
2366 label=None,
2367 nr=None):
2368 if ((name is None) and (type is None) and (kind is None) and
2369 (id is None) and (label is None) and (nr is None)):
2370 raise ValueError(
2371 "at least one argument must be supplied to specify control")
2372
2373 return self._find_control(name, type, kind, id, label, is_listcontrol,
2374 nr)
2375
2376 def _find_control(self, name, type, kind, id, label, predicate, nr):
2377 if ((name is not None) and (name is not Missing) and
2378 not isstringlike(name)):
2379 raise TypeError("control name must be string-like")
2380 if (type is not None) and not isstringlike(type):
2381 raise TypeError("control type must be string-like")
2382 if (kind is not None) and not isstringlike(kind):
2383 raise TypeError("control kind must be string-like")
2384 if (id is not None) and not isstringlike(id):
2385 raise TypeError("control id must be string-like")
2386 if (label is not None) and not isstringlike(label):
2387 raise TypeError("control label must be string-like")
2388 if (predicate is not None) and not callable(predicate):
2389 raise TypeError("control predicate must be callable")
2390 if (nr is not None) and nr < 0:
2391 raise ValueError("control number must be a positive integer")
2392
2393 orig_nr = nr
2394 found = None
2395 ambiguous = False
2396
2397 for control in self.controls:
2398 if ((name is not None and name != control.name) and
2399 (name is not Missing or control.name is not None)):
2400 continue
2401 if type is not None and type != control.type:
2402 continue
2403 if kind is not None and not control.is_of_kind(kind):
2404 continue
2405 if id is not None and id != control.id:
2406 continue
2407 if predicate and not predicate(control):
2408 continue
2409 if label:
2410 for l in control.get_labels():
2411 if l.text.find(label) > -1:
2412 break
2413 else:
2414 continue
2415 if nr is not None:
2416 if nr == 0:
2417 return control # early exit: unambiguous due to nr
2418 nr -= 1
2419 continue
2420 if found:
2421 ambiguous = True
2422 break
2423 found = control
2424
2425 if found and not ambiguous:
2426 return found
2427
2428 description = []
2429 if name is not None:
2430 description.append("name %s" % repr(name))
2431 if type is not None:
2432 description.append("type '%s'" % type)
2433 if kind is not None:
2434 description.append("kind '%s'" % kind)
2435 if id is not None:
2436 description.append("id '%s'" % id)
2437 if label is not None:
2438 description.append("label '%s'" % label)
2439 if predicate is not None:
2440 description.append("predicate %s" % predicate)
2441 if orig_nr:
2442 description.append("nr %d" % orig_nr)
2443 description = ", ".join(description)
2444
2445 if ambiguous:
2446 raise AmbiguityError("more than one control matching " +
2447 description)
2448 elif not found:
2449 raise ControlNotFoundError("no control matching " + description)
2450 assert False
2451
2452 def _click(self,
2453 name,
2454 type,
2455 id,
2456 label,
2457 nr,
2458 coord,
2459 return_type,
2460 request_class=_request.Request):
2461 try:
2462 control = self._find_control(name, type, "clickable", id, label,
2463 None, nr)
2464 except ControlNotFoundError:
2465 if ((name is not None) or (type is not None) or (id is not None) or
2466 (label is not None) or (nr != 0)):
2467 raise
2468 # no clickable controls, but no control was explicitly requested,
2469 # so return state without clicking any control
2470 return self._switch_click(return_type, request_class)
2471 else:
2472 originals = self.method, self.action, self.enctype
2473 try:
2474 if isinstance(control, ScalarControl):
2475 self.method = control.attrs.get(
2476 'formmethod') or self.method
2477 self.action = control.attrs.get(
2478 'formaction') or self.action
2479 self.enctype = control.attrs.get(
2480 'formenctype') or self.enctype
2481 return control._click(self, coord, return_type, request_class)
2482 finally:
2483 self.method, self.action, self.enctype = originals
2484
2485 def _pairs(self):
2486 """Return sequence of (key, value) pairs suitable for urlencoding."""
2487 return [(k, v) for (i, k, v, c_i) in self._pairs_and_controls()]
2488
2489 def _pairs_and_controls(self):
2490 """Return sequence of (index, key, value, control_index)
2491 of totally ordered pairs suitable for urlencoding.
2492
2493 control_index is the index of the control in self.controls
2494 """
2495 pairs = []
2496 for control_index in range(len(self.controls)):
2497 control = self.controls[control_index]
2498 for ii, key, val in control._totally_ordered_pairs():
2499 if ii is None:
2500 ii = -1
2501 pairs.append((ii, key, val, control_index))
2502
2503 # stable sort by ONLY first item in tuple
2504 pairs.sort()
2505
2506 return pairs
2507
2508 def _request_data(self):
2509 """Return a tuple (url, data, headers)."""
2510 method = self.method.upper()
2511 parts = self._urlparse(self.action)
2512 rest, (query, frag) = parts[:-2], parts[-2:]
2513 frag
2514
2515 def encode_data(x):
2516 if isinstance(x, unicode_type):
2517 x = x.encode(self.form_encoding)
2518 return x
2519
2520 def encode_query():
2521 p = [(encode_data(k), encode_data(v)) for k, v in self._pairs()]
2522 return urlencode(p)
2523
2524 if method == "GET":
2525 if self.enctype != "application/x-www-form-urlencoded":
2526 raise ValueError("unknown GET form encoding type '%s'" %
2527 self.enctype)
2528 parts = rest + (encode_query(), None)
2529 uri = self._urlunparse(parts)
2530 return uri, None, []
2531 elif method == "POST":
2532 parts = rest + (query, None)
2533 uri = self._urlunparse(parts)
2534 if self.enctype == "application/x-www-form-urlencoded":
2535 return (uri, encode_query(),
2536 [("Content-Type", self.enctype)])
2537 elif self.enctype == "multipart/form-data":
2538 data = StringIO()
2539 http_hdrs = []
2540 mw = MimeWriter(data, http_hdrs)
2541 mw.startmultipartbody(
2542 "form-data", add_to_http_hdrs=True, prefix=0)
2543 for ii, k, v, control_index in self._pairs_and_controls():
2544 self.controls[control_index]._write_mime_data(
2545 mw, encode_data(k), encode_data(v))
2546 mw.lastpart()
2547 return uri, data.getvalue(), http_hdrs
2548 else:
2549 raise ValueError("unknown POST form encoding type '%s'" %
2550 self.enctype)
2551 else:
2552 raise ValueError("Unknown method '%s'" % method)
2553
2554 def _switch_click(self, return_type, request_class=_request.Request):
2555 # This is called by HTMLForm and clickable Controls to hide switching
2556 # on return_type.
2557 if return_type == "pairs":
2558 return self._pairs()
2559 elif return_type == "request_data":
2560 return self._request_data()
2561 else:
2562 req_data = self._request_data()
2563 req = request_class(req_data[0], req_data[1])
2564 for key, val in req_data[2]:
2565 add_hdr = req.add_header
2566 if key.lower() == "content-type":
2567 try:
2568 add_hdr = req.add_unredirected_header
2569 except AttributeError:
2570 # pre-2.4 and not using ClientCookie
2571 pass
2572 add_hdr(key, val)
2573 return req