首页 > 解决方案 > 使用 Selenium 从 JavaScript 返回值到 Python

问题描述

我试图从这个 javascript 方法“confirm()”返回 True 或 False 到我的 python 变量。但是,它会显示提示,并且程序控件会继续前进并且永远不会返回任何内容。我该如何阻止它这样做?有没有其他方法可以用来从用户那里获取“是”或“否”并将其返回给我的 python 变量?我已经尝试过 prompt() 但我不希望用户输入任何内容。我希望它只是一个简单的“是”或“否”。

choice= self.driver.execute_script(""" if(confirm('Yes or No?')) {
         return true;    
        }
        else{
            return false;
        } """)

if choice == True:
    print('Success!')
else:
    print('Failed')

标签: javascriptpythonselenium

解决方案


基本上这里的问题以及你想如何解决它有点复杂。

首先,javascript 代码无效,执行此脚本将返回None. 脚本的版本要简单得多,driver.execute_script("return confirm('...')")但这里的问题是警报会弹出,python 代码会继续,所以它仍然会返回None

您可以做的是执行confirm('Yes or No?')将其存储在变量中,等到警报消失并返回此变量。

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import NoAlertPresentException

# small helper class to wait untill alert is no longer present
class alert_is_not_present(object):
    """ Expect an alert to not to be present."""
    def __call__(self, driver):
        try:
            alert = driver.switch_to.alert
            alert.text
            return False
        except NoAlertPresentException:
            return True


self.driver.execute_script("choice = confirm('yes or no')")

# Give some large timeout so you're sure that someone will have time to click
# Wait until user makes a choice
WebDriverWait(self.driver, 10000).until(alert_is_not_present())
# retrieve the choice
choice = self.driver.execute_script('return choice')
if choice:
    print('Success!')
else:
    print('Failed')

推荐阅读