2012-05-08 14 views
20

Sto lavorando su mechanize con python.mechanize select form using id

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

Il modulo qui non ha un nome. Come posso analizzare il modulo utilizzando il suo numero id?

risposta

2

provare con:

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

Dovrebbe restituire un elenco di tutti gli ID di forma dalla pagina

+0

grazie ma è writtening elenco vuoto – sam

3

Provare a utilizzare: br.select_form(nr=0), dove nr è il numero di modulo (non è necessario il nome o id).

+1

si dice alcuna forma di corrispondenza nr – sam

+0

Hai provato letteralmente: br.select_form (nr = 0)? – marbdq

+0

si. ho provato lo stesso – sam

20

Ho trovato questo come soluzione per lo stesso problema. br è l'oggetto mechanize:

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

Sono sicuro che il metodo contatore del ciclo di cui sopra potrebbe essere fatto più divinatorio, ma questo dovrebbe selezionare il modulo con l'attributo id="sblock".

14

Migliorare un po 'l'esempio di python412524, la documentazione afferma che questo è valido pure, e lo trovo un po' più pulito:

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

Alcuni moduli non hanno un ID. L'uso di 'form.attrs.get ('id')' nell'istruzione if evita invece un KeyError. – awatts

7

Per eventuali spettatori futuri, ecco un'altra versione utilizzando l'argomento predicate. Si noti che questo potrebbe essere fatto in una sola riga con un lambda, se tu fossi così inclinato:

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

br.select_form(predicate=is_sblock_form) 

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

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

È possibile utilizzare il parametro predicato della funzione select_form del Browser classe. Come questo:

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