Recovering from HTTPError in Mechanize

你说的曾经没有我的故事 提交于 2019-12-03 06:38:53
karnesJ.R

It's been a while since I've written for python, but I think I have a workaround for your problem. Try this method:

import requests
except Mechanize.HTTPError:
    while true: ## DANGER ##
        ## You will need to format and/or decode the POST for your form
        response = requests.post('http://yourwebsite.com/formlink', data=None, json=None)
        ## If the server will accept JSON formatting, this becomes trivial
        if response.status_code == accepted_code: break

You can find documentation about the requests library here. I personally think that requests is better for your case than mechanize... but it does require a little more overhead from you in that you need to break down the submission to raw POST using some kind of RESTful interceptor in your browser.

Ultimately though, by passing in br you are restricting yourself to the way that mechanize handles browser states on br.submit().

I'm assuming that you want the submission to happen even if it takes multiple tries.

The solution that I thought of is certainly not efficient, but it should work.

def do_something_in_mechanize():
    <...insert your code here...>
    try:
        browser.submit()
        <...rest of your code...>
    except mechanize.HTTPError:
        do_something_in_mechanize()

Basically, it'll call the function until the action is performed without HTTPErrors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!