0

我编写了这段代码,它从 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 请求?

4

1 回答 1

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'
             }
于 2013-05-28T13:32:33.520 回答