Search code examples
pythonautomationmechanizewww-mechanize

Python mechanize checkboxes


I want to do this using Python Mechanize. This is HTML page:

<form action="config.php" method="POST">
<div>
<img src="/images/delete1.png" />
<strong>EmptyDir1</strong><br />
<input type="checkbox"  value="3" name="manager[]" />
</div>

<div>
<img src="/images/delete2.png" />
<strong>EmptyDir2</strong><br />
<input type="checkbox"  value="4" name="manager[]" />
</div>

<div>
<img src="/images/copy.png" />
<strong>CopyConf</strong><br />
<input type="checkbox"  value="22" name="manager[]" />
</div>
................. and so on another 20

<div><input type="submit" value="Do Jobs!" /></div>
</form>

I have 2 questions: 1. How can I select all the checkboxes from this page and submit them? 2. How can I select all the checkboxes, except the one with name "modify"? A sample of code will be great. Thanks


Solution

  • Use this for every checkbox:

    import mechanize
    
    br = mechanize.Browser()
    br.open(URL)
    br.select_form(nr=0)
    for i in range(0, len(br.find_control(type="checkbox").items)):
        br.find_control(type="checkbox").items[i].selected =True
    reponse = br.submit()
    print reponse.read()
    

    And this for all except modify checkboxes (haven't checked it):

    import mechanize
    
    br = mechanize.Browser()
    br.open(URL)
    br.select_form(nr=0)
    for i in range(0, len(br.find_control(type="checkbox").items)):
        if "modify" not in str(br.find_control(type="checkbox").items[i]):
            br.find_control(type="checkbox").items[i].selected =True
    reponse = br.submit()
    print reponse.read()