selecting correct form while iterating all forms
<p>I want to submit forms in multiple websites with mechanize. Usually I can't exactly know the form name or form id, but I know the input name that I want to submit.</p>

<p>Let's say there is a website which has couple of forms inside it. My code should check all of the forms, if one of them has a input value named "email" it will submit that form. If multiple forms has it, it will submit them all.</p>

<p>The website which I'm testing has two forms. One of them is login form, the other is subscribe form. Both of them has "email" input value. So my code should submit both forms.</p>

<p>I'm trying to achieve it with this code block:</p>

<pre><code>for forms in br.forms():
                if not forms.find_control(name="email"):
                    continue
                br.select_form(nr=0)        
                br.form["email"] = email
                br.submit()
                print "Success: ", link
</code></pre>

<p>This code prints two success messages, however it's not subscribes. Following code works with submitting subscription form because I set the form name:</p>

<pre><code>br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.6')]
br.open("http://example.com")
br.select_form("subscribe")
br.form["email"] = email
br.submit()
</code></pre>

<p>So what's wrong with the first code? How can I select both forms and submit the value? Probably the problem is with that form selection part:</p>

<pre><code>br.select_form(nr=0)
</code></pre>

<p>Edit: I checked it's POST requests with Wireshark. It seems it fills the first form for 2 times. When I change <code>nr=0</code> with <code>nr=1</code> it works because the correct form is the second form.</p>

<p>Your problem is that you aren't storing what form you are working on. I would simply assign 0 into a variable and add 1 to it after every iteration. So your code should be:</p>

<pre><code>currentForm = 0
for form in br.forms():
        if not forms.find_control(name = "email"):
                currentForm += 1
                continue
        print "Selecting form number %i..." % currentForm
        br.select_form(nr = currentForm)
        br.form["email"] = email
        br.submit()
        currentForm += 1
        print "Success: ", link
</code></pre>

<p>Note: <code>x += y</code> is equal to <code>x = x + y</code></p>

<p>Edit: You should fix your indenting too, you don't need to press tab twice, one press works too!</p>

python mechanize