(NOTE: This came up again recently and I actually got it to work now.)
This seems to work:
br.open(URL) res = mechanize._form.ParseString(FORM_HTML, BASE_URL) br.form = res #continue as if the form was on the page and selected with .select_form() br['username'] = 'foo' br['password'] = 'bar' br.submit()
URL is the full URL of the visited site.
BASE_URL is the directory the URL is in.
FORM_HTML is any HTML that has a
form element, e.g.:
<form method='post' action='/login.aspx'> <input type='text' name='username'> <input type='text' name='password'> <input type='hidden' name='important_js_thing' value='processed_with_python TM'> </form>
For some reason,
mechanize._form.ParseString returns two forms. The first is a
GET request to the base URL with no inputs; the second, the properly parsed form from
Parse the page, extract the elements you want, reform the page, and inject them back into mechanize.
You may or may not run into that problem, but it's something to keep in mind. I ultimately ended up abandoning the Mechanize approach and went with Selenium. It's form handler was far superior and it could handle JS. It's got its issues (the browser adds a layer of complexity), but I found it much easier to work with.
©2020 All rights reserved.