【问题标题】:How can I add an attribute to an html element by id value (python flask lxml)如何通过 id 值向 html 元素添加属性(python flask lxml)
【发布时间】:2022-01-24 05:30:17
【问题描述】:

我想为多个输入元素添加一个值属性。目前,我只是使用一个可以工作但很麻烦的替换。有没有办法通过它的 ID 属性找到一个元素并简单地添加一个 value 属性?

page = render_template('template.html')
page = page.replace('<input type="text" class="form-control" id="Company" name="Company" placeholder="Company name" data-bs-toggle="tooltip" title="The name of the company that the document is for." onblur="titleCase(this)">',
                    '<input type="text" class="form-control" id="Company" name="Company" placeholder="Company name" data-bs-toggle="tooltip" title="The name of the company that the document is for." onblur="titleCase(this)" value="' + company + '">')

有没有办法做到这一点而不会使事情变得过于复杂?

编辑:我在 lxml.html 文档中找到了一个示例,鼓励我这样做:

def fillForm1(page, pDate, company, manager, cAddress, cPhone, cEmail ,sAddress):
form_page = fromstring(page)
form = form_page.forms[0]
form.fields = dict(
    pDate=pDate,
    Company=company,
    Manager=manager,
    cAddress=cAddress,
    cPhone=cPhone,
    cEmail=cEmail,
    sAddress=sAddress
    )
page = page.replace('<form method="post">', tostring(form, pretty_print=True, encoding='UTF-8', with_tail=False,))

return page

但是当它应该是一个字符串时,我一直收到一个关于将字节传回的错误。

【问题讨论】:

    标签: html python-3.x flask lxml


    【解决方案1】:

    由于您使用的是render_template,您可以简单地使用Jinja

    Jinja 可以帮助您安全地在 html 页面中的任意位置呈现数据,并且无需安装任何东西,因为 render_template 方法已经使用了它。

    您需要在 html 文件中指定一个类似于占位符的内容,然后将值作为关键字传递给 render_template

    你需要把它放在你的 HTML 文件中

    <input value="{{company}}" type="text" class="form-control" id="Company" name="Company" placeholder="Company name" data-bs-toggle="tooltip" title="The name of the company that the document is for." onblur="titleCase(this)" >
    

    现在 Jinja 将搜索一个名为 company 的关键字(根据您传递的内容),并将其值替换为 pf {{company}}

    要将值传递给 Jinja,只需在 Python 代码中使用这一行

    company_value = "Some Value"
    page = render_template('template.html', company=company_value)
    

    现在当 Jinja 看到 {{company}} 时,它会将其替换为传递的值,即 company_value = "Some Value" 的值

    请注意,您可以传递任意数量的值


    Jinja 有更多功能可以帮助您呈现数据,例如:

    • 循环
    • if else 语句
    • 还有更多

    查看此文档以快速查看Jinja

    【讨论】:

    • 我工作太久了,我不敢相信我没有看到。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-12-26
    • 2021-11-20
    • 2017-05-02
    • 1970-01-01
    • 2011-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多