我已经开发了一个基于web的工具,目前正试图使其能够启动python。我认为使用Python可能是实现这一点的方法。我按照教程here编写了以下代码:
from cefpython3 import cefpython as cef
import base64
import platform
import sys
import threading
import os
HTML_code = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link href="static/css/main.css" rel="stylesheet" />
</head>
<body>
<div id="UI">
</div>
<div id="container"></div>
<script src="static/main.js"></script>
<script type="text/javascript">
function defineData(datainput){
console.log("start")
data = datainput;
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
console.log(loc);
console.log(dir);
Main();
}
</script>
</body>
</html>
"""
def html_to_data_uri(html):
html = html.encode("utf-8", "replace")
b64 = base64.b64encode(html).decode("utf-8", "replace")
ret = "data:text/html;base64,{data}".format(data=b64)
return ret
def main(config):
sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error
settings = {}
cef.Initialize(settings=settings)
browser = cef.CreateBrowserSync(url=html_to_data_uri(HTML_code),window_title="Test")
browser.SetClientHandler(LoadHandler(config))
cef.MessageLoop()
cef.Shutdown()
return
class LoadHandler(object):
def __init__(self, config):
self.config = config
def OnLoadingStateChange(self, browser, is_loading, **_):
"""Called when the loading state has changed."""
if not is_loading:
# Loading is complete. DOM is ready.
browser.ExecuteFunction("defineData", self.config)
不幸的是,与本教程不同,我的工具必须加载一个本地.js文件,其中定义了主函数(),如果我以这种方式编写html文件,我的工作目录实际上不是调用脚本的目录,而是某个奇怪的地方
这些线路的输出为:
var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));
console.log(loc);
console.log(dir);
输出:
text/html;base64,CjwhRE9DVFlQRSBodG1sPgo8aHRtbCBsYW5nPSJlbiI+Cgk8aGVhZD4KCQk8bWV0YSBjaGFyc2V0PSJ1dGYtOCI+CgkJPG1ldGEgbmFtZT0idmlld3BvcnQiIGNvbnRlbnQ9IndpZHRoPWRldmljZS13aWR0aCwgdXNlci1zY2FsYWJsZT1ubywgbWluaW11bS1zY2FsZT0xLjAsIG1heGltdW0tc2NhbGU9MS4wIj4KCQk8bGluayBocmVmPSJzdGF0aWMvY3NzL21haW4uY3NzIiByZWw9InN0eWxlc2hlZXQiIC8+CgkJPHN0eWxlIHR5cGU9InRleHQvY3NzIj4KCQkJKiB7CgkJCQkuYm9yZGV....
text
你能帮我找到用正确路径在python中硬编码html代码的正确方法吗?也许我需要以某种方式设定路径
PS:我确实尝试过将html代码包含在一个单独的.html文件中,它在Windows机器上运行,但MacOS似乎不喜欢它。由于本教程确实在MAC上运行,所以我尝试将html部分硬编码到python脚本中,并希望它在Windows和MAC上都能运行
嗯,HTML文档已经被{}转换为{a1}的主体,因此文档的U[niversal]R[esource]L[ocator](
window.location
)不是服务器上的位置,而是数据URI本身(您提到的“奇怪的地方”)请记住,URL是URI的一个子集,您通过以下方式将URI作为URL传递给CEF:
因此,只要您使用的是数据URI/URL,我认为
window.location
将不会有帮助。相反,您可以将HTML代码提取到单独的.html
文件中,并将该行更改为:相关问题 更多 >
编程相关推荐