urllib2如何发布包含多个提交按钮的表单

时间:2013-05-28 13:11:13

标签: python post urllib2

我写了这段代码,它从excel文件中读取数据,并应该在网站上提交数据:

import xlrd,urllib2,urllib
book = xlrd.open_workbook("C:\\Users\\file.xls")
sh = book.sheet_by_index(0)
url = 'https://myurl'

for rx in range(sh.nrows):
    riga=sh.row(rx)
    denominazione=riga[0].value 
    descrizione=riga[1].value 
    start=str(riga[2].value)[0:4]   
    end=str(riga[3].value)[0:4]
    area=riga[4].value[0:2]
    form_data = {'denominazione': '%s' % (denominazione.encode('utf-8')),
                 'descrizione': '%s' % (descrizione.encode('utf-8')),
                 'categoria': '5',
                 'contratto':'n',
                 'periodo_dal':'%s' % start,
                 'periodo_al': '%s' % end,
                 'area_1_area':'%s' % area,
                 'area_1_perc':'100%',
                 '@action': 'Save all'
                 }
    params = urllib.urlencode(form_data)
    print params
    response = urllib2.urlopen(url, params)
    print response.msg
    data = response.readlines()

    fd= open("C:\\Users\\output.html","w")
    for idx,item in enumerate(data):
        fd.write(item)
    fd.close()

但它失败了,我想这是因为网站的表单有几个提交按钮。正如你从我的源代码中看到的那样,我试图将POST动作编码为:'@ action':'Save all',但即使这样也行不通。如何使用固定操作设置此POST请求?

1 个答案:

答案 0 :(得分:1)

实测值!

抱歉,我刚回答了我的问题。

要做到这一点,我必须以这种方式将动作编码为通常的参数:

 (X)HTML:
 <input type="submit" class="ult_btn01" value="Save" name="save" />
 <input type="submit" class="ult_btn01" value="Save all" name="save_all" />

 python:
 form_data = {'denominazione': '%s' % (denominazione.encode('utf-8')),
              'descrizione': '%s' % (descrizione.encode('utf-8')),
              'categoria': '5',
              'contratto':'n',
              'periodo_dal':'%s' % start,
              'periodo_al': '%s' % end,
              'area_1_area':'%s' % area,
              'area_1_perc':'100',
              'save_all': 'Save all'
             }