python编写选项,如何使用Python选择表单中的选项?

I'd like to know how to select options in a form that is formatted like

Value1

Value2

Right now, I am using mechanize to connect to the website and traverse to the desired page. This page has many forms such as FORM1, FORM2, FORM3, etc. with options. I'd like to select (enable) Value1 then tell the instance of mechanize to hit the submit button. Which would be a quick way to enable an option based on the form name?

解决方案

Here are some basic usage examples to get you going:

>>> import mechanize

>>> br = mechanize.Browser()

>>> br.open('http://www.w3schools.com/html/html_forms.asp')

Forms have a name attribute; sometimes it's empty though:

>>> [f.name for f in br.forms()]

['searchform', None, None, None, None, 'input0']

Forms have a sequence of controls; controls also have names:

>>> forms = [f for f in br.forms()]

>>> forms[1].controls[0].name

'firstname'

>>> [c.name for c in forms[3].controls]

['sex']

You can get a listing of items in a control:

>>> forms[3].controls[0].get_items()

[, ]

For radio buttons, you have to make a single selection:

>>> forms[3]['sex'] = ['male']

But the selection has to be in a list:

>>> forms[3]['sex'] = 'male'

Traceback (most recent call last):

File "", line 1, in

File "/Library/Python/2.6/site-packages/mechanize/_form.py", line 2782, in __setitem__

control.value = value

File "/Library/Python/2.6/site-packages/mechanize/_form.py", line 1977, in __setattr__

self._set_value(value)

File "/Library/Python/2.6/site-packages/mechanize/_form.py", line 1985, in _set_value

raise TypeError("ListControl, must set a sequence")

TypeError: ListControl, must set a sequence

For check boxes you can make multiple selections:

>>> [(c.name, c.get_items()) for c in forms[4].controls]

[('vehicle', [, ])]

>>> forms[4]['vehicle'] = ['Bike', 'Car']

You can find more info here (link stolen from Matt Hempel :).

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值