在Python中调用网页上的JavaScript代码,可以通过以下几种方法实现:
PyExecJS
安装:`pip install PyExecJS`
示例代码:
```python
import execjs
读取JS文件内容
with open('test.js', 'r', encoding='UTF-8') as file:
js_content = file.read()
编译JS内容
js_context = execjs.compile(js_content)
调用JS函数
result = js_context.call('enString', '')
print(result)
PyQt WebView
使用`webView.page().mainFrame().evaluateJavaScript()`方法。
示例代码:
```python
from PyQt5.QtCore import QUrl
from PyQt5.QtWidgets import QDialog
from PyQt5.QtWebEngineWidgets import QWebEngineView
class MyBrowser(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setupUi(self)
self.webView = QWebEngineView()
self.webView.loadFinished.connect(self._plot)
self.webView.load(QUrl('gpsPoint.html'))
def _plot(self):
result = self.webView.page().mainFrame().evaluateJavaScript('你的JavaScript代码')
print(result)
Selenium
安装:`pip install selenium`
下载对应浏览器的驱动程序(如ChromeDriver)。
示例代码:
```python
from selenium import webdriver
driver = webdriver.Chrome(executable_path='path/to/chromedriver')
driver.get('http://example.com')
执行JavaScript代码
result = driver.execute_script('你的JavaScript代码')
print(result)
driver.quit()
js2py
安装:`pip install js2py`
示例代码:
```python
import js2py
读取JS文件内容
with open('test.js', 'r') as f:
js_content = f.read()
将JS代码转换为Python
content = js2py.EvalJs()
content.execute(js_content)
调用JS函数
result = content.add(1, 2)
print(result)
选择适合你需求的方法进行操作。需要注意的是,不同的方法可能会有不同的兼容性和性能表现,请根据具体情况选择合适的方法