2012-05-08 80 views
20

我正在使用python進行機械化。使用ID機械化選擇表格

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

此處的表格沒有名稱。我怎樣才能解析表單使用它的id

回答

2

嘗試:

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

應該從你的頁面

+0

感謝,但它是writtening空白列表 – sam

3

返回所有形式的ID的列表嘗試使用:br.select_form(nr=0),其中NR是表格編號(不需要名稱或ID)。

+1

它說沒有形式匹配NR – sam

+0

你試過從字面上:br.select_form(NR = 0)? – marbdq

+0

是的。我也嘗試過。 – sam

20

我發現這是針對同一問題的解決方案。 br是機械化對象:

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

我敢肯定,循環計數器上述方法可以做更Python,但這應該與屬性id="sblock"選擇形式。

14

提高對python412524的例子了一下,文檔指出,這是有效的,以及,我覺得有點清潔:

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

某些表單沒有ID。在if語句中使用'form.attrs.get('id')'可以避免KeyError。 – awatts

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 
0

您可以使用瀏覽器的功能select_form的謂語PARAM類。就像這樣:

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")