如何获取JavaScript函数对Python变量的返回值
我试图使用SeleniumWebDriver从网站本地存储中获取一些信息。我使用的是Python3.8.5,我想将JavaScript的输出值返回给python变量如何获取JavaScript函数对Python变量的返回值,javascript,python,selenium,google-chrome,selenium-webdriver,Javascript,Python,Selenium,Google Chrome,Selenium Webdriver,我试图使用SeleniumWebDriver从网站本地存储中获取一些信息。我使用的是Python3.8.5,我想将JavaScript的输出值返回给python变量 number = driver.execute_script("setTimeout(function(){ localStorage.getItem('value'); }, 1500);") 但是当我打印变量number时,由于某种原因,结果是无。关于我应该做什么有什么想法吗?您必须从JS脚本返回: pri
number = driver.execute_script("setTimeout(function(){ localStorage.getItem('value'); }, 1500);")
但是当我打印变量
number
时,由于某种原因,结果是无。关于我应该做什么有什么想法吗?您必须从JS脚本返回:
print(driver.execute_脚本('returnlocalstorage.getItem(“value”);'))
您可以使用以下功能:
number = driver.execute_script("setTimeout(function(){ return localStorage.getItem('value'); }, 1500);")
如果要将任何值从客户端(javascript)传递到后端(python),可以使用ajax在此处发送数据:
但最好的方法是直接通过python获取所需的数据,这将足够快。有许多软件包/库,如selenium、requests和beautiful soap,您可以使用它们来实现这一点。这将导航到此页面,您在其中提出了这个问题,并使用javascript返回localStorage项“se:fkey”:
from selenium import webdriver
driver = webdriver.Chrome(executable_path=r'C:\\Path\\To\\Your\\chromedriver.exe')
driver.get('https://stackoverflow.com/questions/63283026/how-to-get-the-return-value-of-a-javascript-function-to-a-python-variable')
a_returned = driver.execute_script("""
a_function = function(){
console.log(localStorage.getItem("se:fkey"));
return localStorage.getItem("se:fkey");
};
return a_function();
""")
print("a_returned:", a_returned)
口头解释通常是有帮助的