2013-10-14 110 views
0
import mechanize 

br=mechanize.Browser() 
br.set_handle_robots(False) 
formno=-1 

br.open(raw_input("enter the url")) 
allforms=br.forms() 

for form in allforms: 
    print "form name:",form.name 

    print "lets get to work" 

for form in br.forms(): 
    formno=formno+1 
    print "*"*20 
    print "working on form ",form.name 
    #form.set_all_readonly(False) 
    print formno 
    br.select_form(nr=formno) 
    print "boss" 
    for control in br.form.controls: 
     if control.readonly is True: 
      pass 
     else: 
      print control.name 
      form[control.name]='sparsh' 

    resp=br.submit() 
    resp=resp.get_data() 
    print resp 

輸出:蟒蛇機械化形式提交錯誤

enter the url http://www.howtogeek.com/ 
form name: None 
form name: None 
form name: None 
lets get to work 
******************** 
working on form None 
0 
boss 
emailaddress 
emailaddress False 
email 
email False 

One more step! 
Make sure to check your email for a confirmation message. 

Note: If you do not get it soon, check your Spam or Junk folders. 

hello 
******************** 
working on form None 
1 

**Traceback (most recent call last): 
File "D:\thesis\data\form_mechanize_try.py", line 21, in 
br.select_form(nr=formno) 
File "build\bdist.win32\egg\mechanize\_mechanize.py", line 524, in select_form 
raise FormNotFoundError("no form matching "+description) 
FormNotFoundError: no form matching nr 1** 

爲什麼會出現這個錯誤?

什麼,我想實現的是,以填補所有可用的形式在一個特定的網站,看到了迴應..但上面的代碼只是能夠選擇第一種形式,並且給錯誤後

回答

1

你想使用未命名的表單。下面是正確的語法:

# List the forms that are in the page 

for form in br.forms(): 
    print "Form name:", form.name 
    print form 

# To go on the mechanize browser object must have a form selected 
br.select_form(nd = "form1")   # works when form has a name 
br.form = list(br.forms())[0] # use when form is unnamed 

Python的初學者有大約機械化很大的小抄:http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet/