gpt4 book ai didi

Python Selenium 等待用户单击按钮

转载 作者:太空狗 更新时间:2023-10-30 01:18:29 27 4
gpt4 key购买 nike

上下文:

  1. 我的脚本使用 selenium webdriver 启动到网站
  2. 用户在网站上填写一些东西
  3. 用户将单击一个按钮,该按钮将弹出一个 confirm() dialogbox 询问用户“是否要提交数据”

我的意图:

我的脚本会等到用户点击按钮。一旦它检测到用户单击了按钮,我的脚本就会获取一个元素的值,然后(以某种方式)单击 dialog box 上的OK .


问题:

如何等待用户点击按钮?

然后如何在 dialog box 上单击“确定” ?


附加说明:

使用:chromedriver,Python 2.7

按钮:<input id="submitID" type="button" class="medium" value="Submit filled Data">


[编辑] 一些代码片段:

对话框弹出是javascript弹出:

    if (window.confirm("Are you sure you want to submit the data?")) {
this.SaveData();
}

我的代码(针对这个问题进行了简化和修改):

from selenium import webdriver
from selenium.common.exceptions import WebDriverException

PATH_TO_CHROMEDRIVER = 'path/to/chromedriver'
URL = 'https://website-asking-user-to-fill-in-stuff.com'

driver = webdriver.Chrome(PATH_TO_CHROMEDRIVER)
driver.get(URL)

while True:
# loop until user close the chrome.
# If anyone has any better idea to
# WAIT TILL USER CLOSE THE WEBDRIVER, PLEASE SHARE IT HERE

try:
# --- main part of the code ---

waitForUserToClickButton() # this is what I need help with

driver.find_element_by_id('elementID').text

confirmJavascriptPopup() # this is also what I need help with

except WebDriverException:
print 'User closed the browser'
exit()

最佳答案

问:如何等待用户点击按钮?

在这种情况下,可以引入WebDriverWait,也就是selenium中的显式等待

你可以试试这个代码:

from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'submitID')))

问。然后如何单击对话框中的“确定”?

在这种情况下,首先您必须将网络驱动程序的焦点切换到警报,然后您可以单击它。

    alert = browser.switch_to.alert
alert.accept()
print("alert accepted")

更新 1:

当您执行点击操作时,会弹出一个警报。您可以使用以下代码从警报中提取文本:

alert = browser.switch_to.alert
msg_from_alert = alert.text
alert.accept()

现在您可以简单地将它与您已知的预期消息相匹配。

expected_msg = "some msg from alert"  

from collections import Counter
Counter(msg_from_alert) == Counter(expected_msg)
True

关于Python Selenium 等待用户单击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51681276/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com