25

I am working on mechanize with python.

<form action="/monthly-reports"  accept-charset="UTF-8" method="post" id="sblock">

The form here does not have a name. How can I parse the form using it's id?

Moshe
  • 9,283
  • 4
  • 29
  • 38
sam
  • 18,509
  • 24
  • 83
  • 116

7 Answers7

23

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

formcount=0
for frm in br.forms():  
  if str(frm.attrs["id"])=="sblock":
    break
  formcount=formcount+1
br.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".

FoolishSeth
  • 3,953
  • 2
  • 19
  • 28
python412524
  • 266
  • 2
  • 4
15

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
Dan
  • 1,925
  • 3
  • 22
  • 28
  • 5
    Some forms do not have an id. Using `form.attrs.get('id')` in the if statement instead avoids a KeyError. – awatts Apr 30 '15 at 09:11
8

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

Moshe
  • 9,283
  • 4
  • 29
  • 38
3

Try using: br.select_form(nr=0), where nr is the form number (you don't need the name or id).

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
marbdq
  • 1,235
  • 8
  • 5
1

try with:

[f.id for f in br.forms()]

It should return a list of all form ids from your page

Tudor Constantin
  • 26,330
  • 7
  • 49
  • 72
0
g_form_id = ""


def is_form_found(form1):
    return "id" in form1.attrs and form1.attrs['id'] == g_form_id


def select_form_with_id_using_br(br1, id1):
    global g_form_id
    g_form_id = id1
    try:
        br1.select_form(predicate=is_form_found)
    except mechanize.FormNotFoundError:
        print "form not found, id: " + g_form_id
        exit()


# ... goto the form page, using br = mechanize.Browser()

# now lets select a form with id "user-register-form", and print its contents
select_form_with_id_using_br(br, "user-register-form")
print br.form


# that's it, it works! upvote me if u like
Manohar Reddy Poreddy
  • 25,399
  • 9
  • 157
  • 140
0

You can use the predicate param of the function select_form of the Browser class. Like this:

from mechanize import Browser, FormNotFoundError

try:
   br.select_form(predicate=lambda frm: 'id' in frm.attrs and frm.attrs['id'] == 'sblock')
except FormNotFoundError:
  print("ERROR: Form not Found")   
roj4s
  • 251
  • 2
  • 8