javascript - 使用 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')
解决方案
基本上这里的问题以及你想如何解决它有点复杂。
首先,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')
推荐阅读
- gitlab - GitLab CICD 功能如何让指定项目成员执行手动执行
- loops - 冷融合循环正在丢弃链接
- selenium - 如何在没有 Selenium 的情况下制作自动化的帖子作者
- angular - 当某些失败无关紧要时如何处理多个可观察对象?
- excel - Excel 文件另存为 CSV 时总金额相差 1c
- python - 在包缓存中发现没有条目的 Conda 管理的包
- c# - 由于我的 API 返回不同的属性,我应该使用动态对象吗?
- django - 在 curl 命令中添加自定义 id 参数
- node.js - 在 Firebase 中构建用户的收藏夹并将数据写入其中
- python - 如何在 python 中找到数据框列的日志?