使用Python mechanize提交嵌套表单
我正在尝试在一个网页上提交一个登录表单,页面的样子大概是这样的。我也试过提交嵌套的表单,或者同时提交两个表单,但每次都出现同样的错误。
<form method="post" name="loginform">
<input type='hidden' name='login' value='1'>
<form action="#" method="post" id="login">
Username
<input type="text" name="username" id="username" />
Password
<input type="password" name="password" id="password" />
<input type="submit" value='Login' class="submit" />
这是我正在使用的Python脚本。我还注意到这些表单没有用</form>
结束,不知道这是否跟我的问题有关。
from mechanize import Browser
br = Browser()
br.set_handle_robots( False )
br.addheaders = [('User-agent', 'Firefox')]
br.open('http://www.example.com/')
br.select_form(name="loginform")
br['login'] = '1'
br['username'] = 'user'
br['password'] = 'pass'
resp = br.submit()
我遇到的错误是
ParseError: nested FORMs
编辑:
import mechanize
from BeautifulSoup import MinimalSoup
class PrettifyHandler(mechanize.BaseHandler):
def http_response(self, request, response):
if not hasattr(response, "seek"):
response = mechanize.response_seek_wrapper(response)
# only use BeautifulSoup if response is html
if response.info().dict.has_key('content-type') and ('html' in response.info().dict['content-type']):
soup = MinimalSoup (response.get_data())
response.set_data(soup.prettify())
return response
br = mechanize.Browser()
br.add_handler(PrettifyHandler())
br.open('http://example.com/')
br.select_form(nr=1)
br.form['username'] = 'mrsmith'
br.form['password'] = '123abc'
resp = br.submit()
print resp.read()
2 个回答
1
你可以试着找出页面中出问题的部分,然后手动调整一下。比如,我有一个页面出现了嵌套表单的问题,我发现里面有一个
<FORM></FORM>
被放在了另一个表单块里。我还需要删除第一行,因为那一行的格式也不太对。所以你可以试试这样做:
...
resp = br.open(url) # Load login page
# the [111:0] takes away the first 111 chars of the response
# the .replace('<FORM></FORM>','') removes the bad HTML
resp.set_data(resp.get_data()[111:].replace('<FORM></FORM>',''))
br.set_response(resp)
2
试试用 ICantBelieveItsBeautifulSoup 或者 MinimalSoup 这个解析器,代替 BeautifulSoup。具体的实现方法可以参考 这个链接。