Claudiu
Claudiu

Reputation: 229321

python mechanize: create and submit a form

I'm interfacing a website with mechanize. The website creates a custom form using javascript and submits it after creating it. How can I do the same with mechanize, namely: create a form, add the input elements same as the site's javascript does, and submit it?

Upvotes: 1

Views: 2166

Answers (1)

Claudiu
Claudiu

Reputation: 229321

This seems to work:

br.open(URL)
res = mechanize._form.ParseString(FORM_HTML, BASE_URL)
br.form = res[1]
#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 FORM_HTML.

Upvotes: 1

Related Questions