如何在python中获取html数据

时间:2012-06-22 11:30:15

标签: python html flask

我有以下HTML代码

<html>

<head>
<script type="text/javascript">
function processdata()
{
var un=document.getElementById('uname1');
alert("hI " + un.value);
}
</script>
</head>

<body>
Username: <input type="text" name="uname" value=" " id="uname1">
<input type="button" name="sub" onclick="processdata();" value="Submit">

</body>

</html>

这个html页面在python / flask中调用,如下所示 -

@app.route('/')
def getusername():
  return render_template('appHTML.html')

现在我想在python变量中获取字段'uname'中的值。

请告诉我怎么做。 我不是在使用CGI。 我改用烧瓶。

2 个答案:

答案 0 :(得分:1)

您的问题是您没有表单标记 - 因此默认情况下浏览器不会向服务器提交任何内容。

让浏览器将表单提交到服务器的方法就是将输入(包括文本和提交)包装在<form>标记中,其中action属性指向您的URL将接受回应。

所以你的代码看起来像这样(包装代码遗漏):

<form action="/process-form" method="post">
Username: <input type="text" name="uname" value=" " id="uname1">
<input type="button" name="sub" value="Submit">
</form>

如果您愿意,可以使用method="get"而不是method="post",但POST通常是您正在寻找的。然后,您将设置应用程序以处理端点上的发布请求:

from flask import Flask, request

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("your_form_template.html")

@app.route("/process-form", methods=["POST"])
def process():
    username = request.form["uname"]
    return "Hello {}!".format(username)

如果您希望能够将值异步发送回服务器(因此整个页面不会重新加载),那么您可以使用Ajax仅将值提交给服务器。您的页面看起来一样 - 只需使用JavaScript来阻止表单的提交,然后使用POST方法将XHR请求提交回服务器。 (如果这一切都非常令人困惑,你可能会考虑选择一个库来帮助抽象出浏览器之间的一些差异 - 现在jQuery很受欢迎......如果有点过度推荐。)

答案 1 :(得分:-2)

这里有一些解析器的例子

from HTMLParser import HTMLParser
from htmlentitydefs import name2codepoint

class MyHTMLParser(HTMLParser):
    def handle_starttag(self, tag, attrs):
        print "Start tag:", tag
        for attr in attrs:
            print "     attr:", attr
    def handle_endtag(self, tag):
        print "End tag  :", tag
    def handle_data(self, data):
        print "Data     :", data
    def handle_comment(self, data):
        print "Comment  :", data
    def handle_entityref(self, name):
        c = unichr(name2codepoint[name])
        print "Named ent:", c
    def handle_charref(self, name):
        if name.startswith('x'):
            c = unichr(int(name[1:], 16))
        else:
            c = unichr(int(name))
        print "Num ent  :", c
    def handle_decl(self, data):
        print "Decl     :", data

parser = MyHTMLParser()


parser.feed('<h1>Python</h1>')
Start tag: h1
Data     : Python
End tag  : h1