Django:将HTML(包含表单)解析为字典 [英] Django: Parse HTML (containing form) to dictionary
问题描述
我在服务器端创建了一个html表单.
I create a html form on the server side.
<form action="." method="POST">
<input type="text" name="foo" value="bar">
<textarea name="area">long text</textarea>
<select name="your-choice">
<option value="a" selected>A</option>
<option value="b">B</option>
</select>
</form>
所需结果:
{
"foo": "bar",
"area": "long text",
"your-choice": "a",
}
我正在寻找的方法( parse_form()
)可以这样使用:
The method (parse_form()
) I am looking for could be used like this:
response = client.get('/foo/')
# response contains <form> ...</form>
data = parse_form(response.content)
data['my-input']='bar'
response = client.post('/foo/', data)
如何在Python中实现 parse_form()
?
How to implement parse_form()
in Python?
这与Django不相关,但是Django中有一个功能请求,但几年前被拒绝了:
This is not related to Django, nevertheless, there is an feature request in Django, but it was rejected several years ago: https://code.djangoproject.com/ticket/11797
我围绕基于 lxml
的答案编写了一个小型Python库: html_form_to_dict
I wrote a small Python library around the the lxml
based answer: html_form_to_dict
推荐答案
为什么不仅如此?:
def parse_form(content):
import lxml.html
tree = lxml.html.fromstring(content)
return dict(tree.forms[0].fields)
我猜不出使用UserDict的原因
I couldn't guess the reason for using a UserDict
一个小警告:我注意到,当表单包含< select>时,如果未选择任何选项,则返回第一个值;否则,将返回第一个值.我上面基于BS给出的解决方案则返回None
One little caveat: I noticed that when the form contains a <select>, the first value is returned when no option is selected; the solution I gave above based on BS returns None instead
这篇关于Django:将HTML(包含表单)解析为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!