在Mechanize中获取br.forms()的关键和价值

时间:2016-03-31 22:01:51

标签: python forms mechanize

使用Mechanize,我可以获得页面的所有形式。

for f in br.forms():
    print f

对于我的页面,它提供了这样的信息:

<HiddenControl(assoc_term_in=201535) (readonly)>
  <HiddenControl(CRN_IN=34688) (readonly)>
  <HiddenControl(start_date_in=03/28/2016) (readonly)>
  <HiddenControl(end_date_in=06/11/2016) (readonly)>
  <HiddenControl(SUBJ=ECEC) (readonly)>
  <HiddenControl(CRSE=451) (readonly)>
  <HiddenControl(SEC=001) (readonly)>
  <HiddenControl(LEVL=Undergraduate Quarter) (readonly)>
  <HiddenControl(CRED=    3.000) (readonly)>
  <HiddenControl(GMOD=Standard Letter) (readonly)>
  <HiddenControl(TITLE=Computer Arithmetic) (readonly)>
  <HiddenControl(MESG=DUMMY) (readonly)>
  <SelectControl(RSTS_IN=[*, WR])>
  <HiddenControl(assoc_term_in=201535) (readonly)>
  <HiddenControl(CRN_IN=31109) (readonly)>
  <HiddenControl(start_date_in=03/28/2016) (readonly)>
  <HiddenControl(end_date_in=06/11/2016) (readonly)>
  <HiddenControl(SUBJ=BIO) (readonly)>
  <HiddenControl(CRSE=141) (readonly)>
  <HiddenControl(SEC=073) (readonly)>
  <HiddenControl(LEVL=Undergraduate Quarter) (readonly)>
  <HiddenControl(CRED=    0.000) (readonly)>
  <HiddenControl(GMOD=Non Gradeable Unit) (readonly)>
  <HiddenControl(TITLE=Essential Biology) (readonly)>
  <HiddenControl(MESG=DUMMY) (readonly)>
  <SelectControl(RSTS_IN=[*, WD])>

但是,我想打印出f变量中的值,例如只打印TITLESUBJCRSE

ECEC 451 Computer Arithmetic

我尝试使用f.valuef.valuef['TITLE'],但没有运气。

我之前有这个工作,但是当我删除该注释以将代码提交到版本控制时我丢失了代码

1 个答案:

答案 0 :(得分:1)

如果您只想要一个特定的值并且您知道密钥:

In [18]: response = br.open("http://www.w3schools.com/html/html_forms.asp")

In [19]: f = list(br.forms())

In [20]: f[0].get_value("firstname")
Out[20]: 'Mickey'
In [21]: f[0].get_value("lastname")
Out[21]: 'Mouse'

您可以使用f._pairs()访问所有对:

for f in br.forms():
    print(f._pairs())

response = br.open("http://www.w3schools.com/html/html_forms.asp")
for f in br.forms():
    print(f)
    print(f._pairs())

你看到它为你提供了键值对:

<GET http://www.w3schools.com/html/action_page.php application/x-www-form-urlencoded
  <TextControl(firstname=Mickey)>
  <TextControl(lastname=Mouse)>
  <SubmitControl(<None>=Submit) (readonly)>>
[('firstname', 'Mickey'), ('lastname', 'Mouse')]
<GET http://www.w3schools.com/html/action_page.php application/x-www-form-urlencoded
  <TextControl(firstname=Mickey)>
  <TextControl(lastname=Mouse)>
  <SubmitControl(<None>=Submit) (readonly)>>
[('firstname', 'Mickey'), ('lastname', 'Mouse')]
<GET http://www.w3schools.com/html/html_forms.asp application/x-www-form-urlencoded
  <TextControl(err_email=)>
  <TextControl(err_url=) (disabled)>
  <TextareaControl(err_desc=)>
  <IgnoreControl(<None>=<None>)>>
[('err_email', ''), ('err_desc', '')]