如何在pywebview加载URL后向DOM插入CSS、JS及HTML文件
在pywebview加载的页面中插入本地CSS、JS、HTML到DOM
直接用evaluate_js()执行原生JS操作DOM是最简洁的方案,比用BS4来回解析HTML高效得多,还不会破坏原页面的状态,具体实现如下:
1. 插入本地CSS
创建<link>标签并插入到页面<head>,用绝对路径确保能正确读取本地文件:
import webview import os def inject_resources(window): # 本地CSS文件路径 css_path = os.path.abspath("local_style.css") # 执行JS插入CSS window.evaluate_js(f''' const cssLink = document.createElement('link'); cssLink.rel = 'stylesheet'; cssLink.href = 'file://{css_path}'; document.head.appendChild(cssLink); ''') if __name__ == '__main__': window = webview.create_window('Inject Demo', 'https://www.amazon.de') webview.start(inject_resources, window)
2. 插入本地JS
创建<script>标签,推荐插入到<body>末尾,确保页面DOM加载完成后再执行脚本:
# 在inject_resources函数内继续添加 js_path = os.path.abspath("local_script.js") window.evaluate_js(f''' const jsScript = document.createElement('script'); jsScript.src = 'file://{js_path}'; document.body.appendChild(jsScript); ''')
3. 插入本地HTML片段
先读取本地HTML文件内容,再创建元素插入到页面指定位置(示例为body末尾):
# 在inject_resources函数内继续添加 html_path = os.path.abspath("local_content.html") with open(html_path, 'r', encoding='utf-8') as f: html_content = f.read() window.evaluate_js(f''' const container = document.createElement('div'); container.innerHTML = `{html_content}`; document.body.appendChild(container); // 若需插入到指定元素,比如id为target的容器: // document.getElementById('target').appendChild(container); ''')
为啥不推荐用BS4?
用BS4需要先拉取整个HTML,解析修改后再重新赋值给页面,这会导致整个页面重新渲染,原页面的用户输入、JS绑定事件都会丢失,步骤繁琐且完全没必要。
内容的提问来源于stack exchange,提问作者marv
相关产品推荐
相关产品推荐

