2012-06-30 87 views
1

的Python我想用填寫此表的Python:發送POST參數,使用機械化

<form method="post" enctype="multipart/form-data" id="uploadimage"> 
    <input type="file" name="image" id="image" /> 
    <input type="submit" name="button" id="button" value="Upload File" class="inputbuttons" /> 
    <input name="newimage" type="hidden" id="image" value="1" /> 
    <input name="path" type="hidden" id="imagepath" value="/var/www/httpdocs/images/" /> 
</form> 

正如你所看到的,也有被命名完全一樣的兩個參數,所以,當我使用機械化要做到這一點,是什麼樣子的:

import mechanize 
    br = mechanize.Browser() 
    br.open('www.site.tld/upload.php') 
    br.select_form(nr=0) 

    br.form['image'] = '/home/user/Desktop/image.jpg' 
    br.submit() 

我收到錯誤:

mechanize._form.AmbiguityError: more than one control matching name 'image' 

每S我在互聯網(包括本網站)找到的解決方案沒有奏效。有不同的方法嗎? 重命名HTML表單中的輸入可能不是一個選項。

在此先感謝。

+1

你知道有兩個具有相同ID的元素是__illegal__ HTML嗎? – orlp

回答

0

您應該改用find_control;如果不明確,您可以添加nr關鍵字來選擇特定控件。在你的情況下,nametype關鍵字應該這樣做。

另請注意,文件控件不需要value;使用add_file代替,並通過在一個打開的文件對象:

br.form.find_control(name='image', type='file').add_file(
    open('/home/user/Desktop/image.jpg', 'rb'), 'image/jpg', 'image.jpg') 

documentation on forms in mechanize