Python Mechanize选择表单FormNotFoundError

时间:2011-10-06 11:54:54

标签: python mechanize mechanize-python

我想选择一个带机械化的表格。这是我的代码:

br = mechanize.Browser()
self.br.open(url)
br.select_form(name="login_form")

表单的代码:

<form id="login_form" onsubmit="return Index.login_submit();" method="post" action="index.php?action=login&server_list=1">

但是我收到了这个错误:

mechanize._mechanize.FormNotFoundError: no form matching name 'login_form

2 个答案:

答案 0 :(得分:23)

问题是您的表单没有名称,只有ID,而且是login_form。您可以使用谓词:

br.select_form(predicate=lambda f: f.attrs.get('id', None) == 'login_form')

(如果f.attrs的密钥为id,则为se,如果是,则id值等于login_form)。或者,您可以传递页面中的表单编号,如果您知道它是第一个,第二个是等等。例如,下面的行选择第一个表单:

br.select_form(nr=0)

答案 1 :(得分:1)

更具可读性:

class Element_by_id:
    def __init__(self, id_text):
        self.id_text = id_text
    def __call__(self, f, *args, **kwargs):
        return 'id' in f.attrs and f.attrs['id'] ==self.id_text

然后:

b.select_form(predicate=Element_by_id("login_form"))
相关问题