在Python中获取JavaScript返回值通常有以下几种方法:
使用Selenium的`execute_script`方法
确保在JavaScript代码中使用`return`关键字来返回值。
示例代码:
from selenium import webdriverjs = "return document.getElementById('input-286').value;"a = driver.execute_script(js)print(a) 输出:获取到的值
使用execjs库
安装execjs库:`pip install execjs`
示例代码:
import execjsjs = """function generateRandomString(length) {var result = '';var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0';var charactersLength = characters.length;for (var i = 0; i < length; i++) {result += characters.charAt(Math.floor(Math.random() * charactersLength));}return result;}"""result = execjs.eval(js)print(result) 输出:随机字符串

使用Node.js命令行
确保电脑上安装了Node.js。
示例代码:
import subprocesscommand = subprocess.run(["node", "add.js", "init", "3", "5"], capture_output=True, text=True)print(command.stdout.strip()) 输出:Node.js执行结果
使用Python中的BeautifulSoup
示例代码:
from bs4 import BeautifulSoupimport redata = """var my = 'hello';var name = 'hi';var is = 'halo';"""soup = BeautifulSoup(data, 'html.parser')pattern = re.compile(r'var my')script = soup.find('script', text=pattern)print(pattern.search(script.text).group(1)) 输出:hello
请根据您的具体需求选择合适的方法。
