使用动态下拉选择的Python机械化

时间:2010-11-02 07:25:11

标签: python webforms drop-down-menu mechanize

我正在使用mechanize来填充表单,我遇到了依赖于之前选择的动态填充下拉列表的问题。

在机械化方面,我做了类似的事情来选择类别:

import mechanize
br = mechanize.Browser()
"""Select the form and set up the browser"""
br["state"] = ["California"]
br["city"] = ["San Francisco"] # this is where the error is
br.submit()

在我选择州为“加利福尼亚州”之前,我无法选择城市为“旧金山”,因为选择“加利福尼亚”后,城市下拉列表会动态填充。

如何使用Python提交城市并进行机械化?

1 个答案:

答案 0 :(得分:1)

mechanize不支持JavaScript。相反,您应该使用urllib2发送所需的值。

import urllib2
import urllib

values = dict(state="CA", city="SF") # examine form for actual vars
try:
    req = urllib2.Request("http://example.com/post.php",
                          urllib.urlencode(values))
    response_page = urllib2.urlopen(req).read()
except urllib2.HTTPError, details:
    pass #do something with the error here...