我有一个脚本可以将一堆JavaScript文件读入变量,然后将这些文件的内容放入Python模板中的占位符中。这导致变量src
(如下所述)的值是包含脚本的有效HTML文档。
# Open the source HTML file to get the paths to the JavaScript files
f = open(srcfile.html, 'rU')
src = f.read()
f.close()
js_scripts = re.findall('script\ssrc="(.*)"', src)
# Put all of the scripts in a variable
js = ''
for script in js_scripts:
f = open(script, 'rU')
js = js + f.read() + '\n'
f.close()
# Open/read the template
template = open('template.html)
templateSrc = Template(template.read())
# Substitute the scripts for the placeholder variable
src = str(templateSrc.safe_substitute(javascript_content=js))
# Write a Python file containing the string
with open('htmlSource.py', 'w') as f:
f.write('#-*- coding: utf-8 -*-\n\nhtmlSrc = """' + src + '"""')
如果我尝试通过Python中的PyQt5 / QtWebKit打开它......
from htmlSource import htmlSrc
webWidget.setHtml(htmlSrc)
...它不会在Web小部件中加载JS文件。我最后得到一个空白页。
但是,如果我摆脱其他所有内容,只需写入文件'"""src"""'
,当我在Chrome中打开文件时,它会按预期加载所有内容。同样,如果我从文件中读取它,它也会在Web小部件中正确加载:
f = open('htmlSource.py', 'r')
htmlSrc = f.read()
webWidget.setHtml(htmlSrc)
换句话说,当我运行这个脚本时,它会生成带有变量的Python输出文件;然后我尝试导入该变量并将其传递给webWidget.setHtml()
;但页面不呈现。但是,如果我使用open()
并将其作为文件读取,则确实如此。
我怀疑这里存在编码问题。但我尝试了encode
和decode
的几种变体而没有任何运气。这些脚本都是UTF-8。
有什么建议吗?非常感谢!