33

I am attempting to have mechanize select a form from a page, but the form in question has no "name" attribute in the html. What should I do? when I try to use

br.select_form(name = "")

I get errors that no form is declared with that name, and the function requires a name input. There is only one form on the page, is there some other way I can select that form?

Mantas Vidutis
  • 16,376
  • 20
  • 76
  • 92

2 Answers2

57

Try:

br.select_form(nr=0)

to select the first form

In Mechanize source,

def select_form(self, name=None, predicate=None, <b>nr=None</b>):
    """
    ...
    nr, if supplied, is the sequence number of the form (where 0 is the
    first).
    """
David Cain
  • 16,484
  • 14
  • 65
  • 75
YOU
  • 120,166
  • 34
  • 186
  • 219
  • Thanks. That worked for my instance with only one form. Just out of curiosity, how do you think it could be done with many forms? Either all unnamed or some named and others unnamed? – Mantas Vidutis Apr 06 '10 at 04:13
  • 1
    @mvid, yeah, a document could have many forms and names are optional too, and mechanize should be no problem with that. – YOU Apr 06 '10 at 04:18
  • where we can get predicate value from form ? – Yuda Prawira Nov 03 '10 at 16:17
  • 1
    @Gunslinger_: predicate is a function that takes the form and returns True or False whether to select it or not – Claudiu Sep 20 '12 at 22:07
2

If you want to execute code for multiple forms no matter what their name is, you can loop over every form letting your script knowing which form will work next.

currentForm = 0
for form in br.forms(): # Iterate over the forms
        br.select_form(nr = currentForm) # Select the form
        '''
        The code you want to run for every form
        '''
        currentForm += 1 # Add 1 to the current working form so the script knows what form is working next
Stam Kaly
  • 668
  • 1
  • 11
  • 26