通过python mechanize上传文件

通过python mechanize上传文件,python,mechanize,mechanize-python,Python,Mechanize,Mechanize Python,我正在尝试使用mechanize将图像文件上载到浏览器中。 虽然没有错误,但当我在浏览器中手动检查时(提交/保存后),上载的文件不会反映出来。 我正在使用以下代码上载文件 import mechanize as mc br = mc.Browser() br.set_handle_robots(False) br.select_form(nr=0) br.form.add_file(open("test.png"), content_type="image/png",

我正在尝试使用mechanize将图像文件上载到浏览器中。 虽然没有错误,但当我在浏览器中手动检查时(提交/保存后),上载的文件不会反映出来。 我正在使用以下代码上载文件

import mechanize as mc
br = mc.Browser()
br.set_handle_robots(False)
br.select_form(nr=0)
br.form.add_file(open("test.png"), content_type="image/png",
             filename='before',name="ctl00$ContentPlaceHolder1$fileuploadBeforeimages")

br.submit("ctl00$ContentPlaceHolder1$cmdSave") 
# this is supposed to save the form on the webpage. It saves the texts in the other fields, whereas the image does not show up.
“添加文件”命令似乎有效。我可以确认这一点,因为当我打印
br.forms()[0]
时,会显示文件详细信息(

但是没有任何迹象表明此代码片段后的图像文件。我已经检查了几个示例,其中包括
br.submit()
,没有任何特定的按钮控件,当我执行此操作时,网站上不会保存任何页面

我错过了什么

提前谢谢

编辑 当我手动尝试上传文件时,我看到一个弹出窗口要求确认。在检查中,这是作为

onchange="if (confirm('Upload ' + this.value + '?')) this.form.submit();" 

我不确定这是否是一个
JavaScript
元素,mechanize不能通过这个部分来实现上传功能。有人能确认一下吗?

您可以在图像名称前面加上“rb”,如下所示:

br.form.add_file(open("test.png",'rb'),'images/png',filename,name='file') 

您可以将“rb”放在图像名称前面,如下所示:

br.form.add_file(open("test.png",'rb'),'images/png',filename,name='file') 

不,它不起作用。谢谢你的回答。不,它不起作用。谢谢你的回答。错误是怎么说的?一点错误都没有。脚本运行正常。是否尝试使用“”单括号?我有过这样的案例,当它起作用的时候。现在尝试过,它似乎没有任何效果。错误说明了什么?一点错误都没有。脚本运行正常。是否尝试使用“”单括号?我曾经有过这样的案例,当它起作用的时候。现在尝试过,它似乎没有任何效果。