简体   繁体   English

用 Python 填写 HTML 输入表单

[英]Fill in HTML input form with Python

I want to fill in a HTML input field with Python.(The HTML page is local on the computer in the same file.) I have this HTML form:我想用 Python 填写一个 HTML 输入字段。(HTML 页面在计算机本地的同一个文件中。)我有这个 HTML 表单:

<body>
    <h1>Person</h1>
    <form class="frame">
        <label for="name">Name:</label><br>
        <input type="text" name="name" id="nameID" value="{p1:}"><br>
        
        <label for="lastname">Last Name:</label><br>
        <input type="text" name="lastname" id="lastnameID" value="{p2:}" ><br>
    </form>
</body>

I have tried this but it doesn't work:我试过这个,但它不起作用:

index = webbrowser.open(url).read().format(p1='World', p2='Hello')

Can anyone help here?有人可以帮忙吗? Thanks in advance!提前致谢!

Since library webbrowser have no connection between your browser and your code.由于库webbrowser在您的浏览器和您的代码之间没有连接。 This is impossible to do that.这是不可能做到的。

If you really want to do that.如果你真的想这样做。 You have two ways.你有两种方法。

  1. Format your html contents first, then open it in browser.首先格式化您的 html 内容,然后在浏览器中打开它。
import webbrowser
import os

html = '<html> ...  String {string} ! ...</html>'.format(string='haha')
path = os.path.abspath('temp.html')
url = 'file://' + path

with open(path, 'w') as f:
    f.write(html)
webbrowser.open(url)

Note: To format the HTML page, you better using template engine library like jinja2 which usually cooperates with server library like flask to serve the formatted page.注意:要格式化HTML页面,最好使用jinja2等模板引擎库,它通常与flask等服务器库配合为格式化的页面提供服务。

  1. Use browser automation library like Selenium or playwright to control your whole webpage.使用Seleniumplaywright等浏览器自动化库来控制整个网页。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM