user1008791
user1008791

Reputation: 1409

Python Mechanize module, selecting all input fields within a form

I need Mechanize to put a certain string into every edittable input field within a selected from. Here is some HTML code as an example:

<form action = "http://localhost/whatever.php" method = "post">
<input type = "hidden" name = "dummy" value = "12345">
<input type = "text" name = "msg"> <br/>
<input type = "text" name = "name"> <br/>
<input type = "submit" value = "Send">
</form>

Since my Python script would be very tedious to re-write on every website, and would become very website dependent, I want it to select all edittable input fields (while not editting hidden or disabled fields) within a selected form and set the value of each input field to a certain string. However, I will not know the names of each input element. So is there a way in which I can select an input element by its index number? My code looks something like this so far:

import mechanize
browser = mechanize.Browser()
url = raw_input("Enter web address: ")
browser.open(url)
browser.select_form(nr=0)
# I know the index number of the form or my Python code will find out which it is
# but I do not know the names of the input elements within this form

And at that point, I would want to do something like this: figure out how many editable input elements exist, and select each one by its index number setting it to a value. So can this be done? I just need an automated way of selecting input fields and setting them to a value without knowing their name or id. Is it possible to select it by its index number, like something like this:

browser.input_elements[1] = "whatever"

In which case is there a list or sequence in Mechanize containing the input elements and values, so I can edit them?

Upvotes: 2

Views: 2945

Answers (1)

TomKo
TomKo

Reputation: 129

Found something that might be of use here:

http://stockrt.github.com/p/emulating-a-browser-in-python-with-mechanize/

# Select the first (index zero) form
br.select_form(nr=0)

Upvotes: 1

Related Questions