2014-11-21 54 views
3

我想在表單的文本字段中輸入一些文本。這是我現在的代碼。接下來我應該做什麼?Python - 機械化輸入文本形式

import re 
from mechanize import Browser 

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

## What should I code here to input text into the form? 

response = br.submit() 

回答

2
br.form['id'] = 'ss-form' # This does the input 
br.submit() # This will submit the form 
print br.response().read() # This will read the new page returned 

嘗試print br.response().read()。這就是你想要的,你可以用美麗的湯來解析迴應。 soup = BeautifulSoup(br.response().read())

+0

br.form ['id'] ='ss-form'不適用於輸入。 這就是我得到的 - 文件「/usr/lib/python2.7/dist-packages/mechanize/_form.py」,第3101行,在find_control中 返回self._find_control(name,type,kind,id,label ,謂詞,nr) 文件「/usr/lib/python2.7/dist-packages/mechanize/_form.py」,第3185行,在_find_control中 raise ControlNotFoundError(「no control matching」+ description) mechanize._form。 ControlNotFoundError:沒有控制匹配名稱'ss-form' – 2014-11-21 05:54:39

+0

我正在管理提交一個空表單,但無法提交任何文本。也許現在你得到了我想要做的事情? – 2014-11-21 05:55:38

+0

這意味着表單不具備該控件。 YOu首先必須通過'br.select_form('name_of_the_form')'選擇正確的表單。 – ssm 2014-11-21 06:03:41

0

如果窗體未命名,你可以使用:

br.select_form(nr=0) 

這將選擇第一個表單(「第0一」)。