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

Getting the key and value of br.forms() in 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'],但没有成功。

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

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

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', '')]