Recovering from HTTPError in Mechanize

前端 未结 2 810
-上瘾入骨i
-上瘾入骨i 2021-02-08 01:40

I am writing a function for some existing python code that will be passed a Mechanize browser object as a parameter.

I fill in some details in a form in the browser, and

相关标签:
2条回答
  • 2021-02-08 02:04

    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.

    0 讨论(0)
  • 2021-02-08 02:11

    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().

    0 讨论(0)
提交回复
热议问题