Mechanize 提交
我们有一个表单,里面有几个不同的提交按钮,每个按钮执行不同的操作。问题是,我有几个按钮的HTML代码如下:
<input type="submit" name="submit" value="Submit" class="submitLink" title="Submit" />
<input type="submit" name="submit" value="Delete" class="submitLink" title="Delete" />
现在,你不能通过值来定位一个元素,使用标准的find_control函数是行不通的。所以我写了一个谓词函数,用来找到我的元素,然后我希望能像这样点击它:
submit_button = self.br.form.find_control(predicate=submit_button_finder)
self.br.submit(submit_button)
但是,submit和click这两个方法内部都调用了find element,而这两个方法都不允许你添加谓词关键字,所以像这样的调用也不行:
self.br.submit(predicate=submit_button_finder)
我是不是遗漏了什么呢?!
更新:
我添加了一个辅助函数,用来获取所有符合条件的元素,如下:
def find_controls(self, name=None, type=None, kind=None, id=None, predicate=None, label=None):
i = 0
results = []
try :
while(True):
results.append(self.browswer.find_control(name, type, kind, id, predicate, label, nr=i))
i += 1
except Exception as e: #Exception tossed if control not found
pass
return results
然后把以下几行代码替换成:
submit_button = self.br.form.find_control(predicate=submit_button_finder)
self.br.submit(submit_button)
变成:
submit_button = self.br.form.find_control(predicate=submit_button_finder)
submit_buttons = self.find_controls(type="submit")
for button in submit_buttons[:]:
if (button != submit_button) : self.br.form.controls.remove(button)
self.br.submit()
1 个回答
3
一个比较简单的方法是手动遍历你想要处理的表单中的所有控件,然后根据一些条件把你不想要的控件从表单中移除。例如:
for each in form.controls[:]:
if each not "some criteria":
form.controls.remove(each)
这里最好的做法是只遍历提交控件(SubmitControl)对象。这样,你的表单就只会有一个提交按钮,浏览器在调用submit()方法时就没有其他按钮可以选择了。