How to get the text input given by a user for an HTML page through python?
e.g.
<html>
<input id="post_form_id" name="fooput" value="" />
</html>
Now, the user inputs the value abcxyz in the text field. How can I get that value using python? I already know how it is done through javascript but I want to do it using python.
Also, I already tried Beautiful Soup but it can only return the preset value of the field. SO I can do
soup=BeautifulSoup(open("myhtmldoc.htm"))
print soup.find('input')['value']
But this wil only give me the preset value and not the value given by the user.
2 Answers 2
You need to write a script that is called when the form is submitted. Typically, you use some framework that takes care of the sundry details.
A lightweight framework like Flask makes this task easy:
from flask import Flask, render_template
app = Flask(__name__)
app.route('/',methods=['GET','POST'])
def print_form():
if request.method == 'POST':
return render_template('form.html',result=request.form['fooput'])
if request.method == 'GET':
return render_template('form.html')
if __name__ == '__main__':
app.run()
In your form.html:
{% if result %}
You entered: {{ result }}
{% endif %}
<form method="POST" action=".">
<input id="post_form_id" name="fooput" value="" />
<input type="submit">
</form>
Comments
Very good documentation:http://flask.pocoo.org/docs/0.10/quickstart/ Have a look.
EDIT: a little bit faster to find: http://flask.pocoo.org/docs/0.10/quickstart/#accessing-request-data