mechanize select form using id mechanize select form using id python python

mechanize select form using id


I found this as a solution for the same problem. br is the mechanize object:

formcount=0for frm in br.forms():    if str(frm.attrs["id"])=="sblock":    break  formcount=formcount+1br.select_form(nr=formcount)

I'm sure the loop counter method above could be done more pythonic, but this should select the form with attribute id="sblock".


Improving a bit on python412524's example, the documentation states that this is valid as well, and I find it a bit cleaner:

for form in br.forms():    if form.attrs['id'] == 'sblock':        br.form = form        break


For any future viewers, here's another version using the predicate argument. Note that this could be made into a single line with a lambda, if you were so inclined:

def is_sblock_form(form):    return "id" in form.attrs and form.attrs['id'] == "sblock"br.select_form(predicate=is_sblock_form)

Source: https://github.com/jjlee/mechanize/blob/master/mechanize/_mechanize.py#L462