简体   繁体   English

如何使用Python 3.7在浏览器中运行html代码?

[英]How do I run an html code in browser using Python 3.7?

Got an HTML code stored in a variable in Python script, I need the browser to open with my HTML. 在Python脚本中有一个存储在变量中的HTML代码,我需要使用我的HTML打开浏览器。 Thanks. 谢谢。

You can do with many ways one of the below : 您可以通过以下方式之一进行以下操作:

import os
import webbrowser

html = '<html>Hello World</html>'
path = os.path.abspath('sample.html')
url = 'file://' + path

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

Save the following HTML to a file: 将以下HTML保存到文件中:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="utf-8" />
  <title>Hello World!</title>
</head>
<body>
  <h1>Hello World!</h1>
  <p>This is a HTML document!</p>
</body>
</html>

Then add the following code to your python script: 然后将以下代码添加到python脚本:

import webbrowser
webbrowser.open("file://path/to/document.html")

Good luck. 祝好运。

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

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