【问题标题】:form table as dictionary input python表格作为字典输入python
【发布时间】:2018-09-26 05:39:31
【问题描述】:

我想创建一个 html 表单来编辑一些数据库表。

我尝试创建一个带有表格的表格,其中每个表格行是数据库表格的一个条目,如下所示:

<form action="/adjust_table.py" method="post">
  <table>
    <tr>
    <td colspan = 4><input type="text" name="id" value="123" readonly></td>
    <td colspan = 4>name: George</td>
    <td colspan = 4>age: <input type="text" name="age[123]" value="73"></td>
    </tr>
    <tr>
    <td colspan = 4><input type="text" name="id" value="1269" readonly></td>
    <td colspan = 4>name: Jake</td>
    <td colspan = 4>age: <input type="text" name="age[1269]" value="26"></td>
    </tr>
    <input type="submit" value="Submit">
  </table>
</form>

但我无法将这些值放入字典或 pandas 数据框中,因此我可以遍历它并更新表格。甚至可以只获取 id 列表和年龄列表,然后遍历它们(如果它们保持正确的顺序)。

数据库中的表有结构id、name、age。 然后需要设置或调整所有行的年龄,所以我想通过 id 来更新年龄。

【问题讨论】:

  • 你想使用python脚本从html表单中提取值吗?
  • @Rachitkapadia 是的,我想循环表单数据并在 mysql 中执行更新。
  • @user3605780 - 你能给我们你的adjust_table.py文件吗?

标签: javascript python forms html-table


【解决方案1】:

你可以使用 python-form-parser

from lxml import etree
from urllib import urlencode

html_string = """
    <html>
        <body>
            <form action="my_path", method="POST" id="my_form">
                  <input type="text" name="my_field" value="my_value"/>
                  <input type="text" name="my_field2"/>
                  <input type="submit" name="my_submit" value="Submit the form"/>
            </form>
        </body>
    </html>
"""

# parse and extract the form
tree = etree.HTML(html_string)
form = tree.xpath("//form[@id='my_form']")[0]

# Extract default values and meta information
ff = FormFiller(form)

# click to 'my_submit' button: will return dictionary with all fields values
form_data = ff.click('my_submit')
print form_data
{"my_field": "my_value",
 "my_submit": "Submit the form"}

# fill user data
form_data['some_name'] = 'some_value'

# prefered way on how to fill user data:
print ff.fill('my_submit', my_field2="my_value2")
{"my_field": "my_value",
 "my_field2": "my_value2",
 "my_submit": "Submit the form"}

# fields that not present on the original form are not allowed
ff.fill('my_submit', field_not_present_in_form_name="my_value3")
KeyError: 'Invalid form field'

# prepare data for sending
body = urlencode(form_data)
url = ff.get_action_url("http://example.com/forms/my_form.html")
print url
'http://example.com/forms/my_path'  # my_path from form's "action" attribute
method = ff.get_method()
print method
'POST'  # from form's "method" attr (GET is default)

【讨论】:

  • 这不是正确的答案。 OP 想edit some mysql tables 而在 python 中解析和填充 html 并没有给他这样的机会。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
  • 2016-10-10
  • 1970-01-01
相关资源
最近更新 更多