Python机械化以提交表单数据

时间:2015-06-26 16:53:57

标签: python forms web-scraping mechanize

我的表单HTML源代码如下,我正在尝试“选中其中一个复选框”并点击“更新”或使用mechanize提交按钮。我该怎么做? linear_entitlements的变量是否不可能?

<form accept-charset="UTF-8" action="/admin/users/3548003/user_linear_entitlements" class="form with-border" id="edit_user_3548003" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="_method" type="hidden" value="put"><input name="authenticity_token" type="hidden" value="samplevalue"></div>
    <table class="table table-striped">
        <thead>
            <tr>
                <th>Name</th>
                <th>GUID</th>
                <th>CMS Subpack ID</th>
                <th>Last Updated</th>
            </tr>
        </thead>
        <tbody>
            <tr id="linear_entitlement_1">
                <td>
                    <div class="control-group">
                        <label class="checkbox">
                            <span>SUN Pack</span>
                            <input class="checkbox" id="user_linear_entitlement_ids_" name="user[linear_entitlement_ids][]" type="checkbox" value="1">
                                </label>
                    </div>
                </td>
                <td> 2a59739c-13ed-11e2-a36b-12313d298802 </td>
                <td> 1 </td>
                <td> 2014-02-12 21:32:56 UTC <div style="float:right"><a href="/admin/linear_entitlements/1">→</a></div></td>
            </tr>
            
            <tr id="linear_entitlement_7">
                <td>
                    <div class="control-group">
                        <label class="checkbox">
                            <span>Tamil Pack - Legacy</span>
                            <input class="checkbox" id="user_linear_entitlement_ids_" name="user[linear_entitlement_ids][]" type="checkbox" value="7">
                                </label>
                    </div>
                </td>
                <td> 2ab298dc-13ed-11e2-a36b-12313d298802 </td>
                <td> 3 </td>
                <td> 2015-04-01 23:11:33 UTC <div style="float:right"><a href="/admin/linear_entitlements/7">→</a></div></td>
            </tr>
        </tbody>
    </table>
    <div class="form-actions">
        <input class="btn primary input_submit" name="commit" type="submit" value="Update">&nbsp;<button type="reset" class="btn">Cancel</button>
    </div>
    
</form>

到目前为止,我有这个,选择表格:

htmlResponse2 = browser.open(URL + 'admin/users/' + old_user_url + '/edit')
browser.select_form(nr=0)

1 个答案:

答案 0 :(得分:2)

我不知道你是否需要选择表格,但是如果你这样做,下面应该只是这样做:

br.find_control(type="checkbox").items[0].selected=True

如果要选中所有复选框:

for i in range(0, len(br.find_control(type="checkbox").items)):
br.find_control(type="checkbox").items[i].selected =True

然后提交

br.submit()