使用Python的Mechanize发送POST请求时表单问题

1 投票
1 回答
3928 浏览
提问于 2025-04-16 19:27

我在用Python的mechanize库填写一个表单,但用普通的submit()方法没成功。奇怪的是,mechanize没有正确识别单选按钮,只找到了1个,而不是4个。之后我尝试写一个POST请求 -

    data = {
        'localid' : '11755',
        'language' : '3',
        'code' : 'hello world',
    }
    page = browser.open( self.submiturl, urllib.urlencode( data) )

但是它根本没有发送任何东西。我不太确定我漏掉了什么,这样做是正确的POST方式吗?有没有其他方法可以让mechanize识别单选按钮?

我的完整代码可以在这个链接中查看。

1 个回答

2

听起来 mechanize 在解析表单时遇到了问题,可以试试下面这样的做法。

br = mechanize.Browser()
resp = br.open('your_url_here')
print resp.get_data() # if you want to see what's returned
# if you want to see the forms, so you can find the index of the
# form you want and check that is has all the fields, if it doesn't
# you should should parse the response with BeautifulSoup
for form in br.forms():
    print '---------------'
    print form
br.select_form(nr=0) # to select the first form
br['field_name'] = 'field_value'
br['select_field_name'] = ['select_field_value']
br.submit()

撰写回答