在Selenium Python上处理javascript对话框
问题描述:
我正在Python上使用Selenium webdriver编写一个网页的自动化代码。但是,在某个时候它要求Captcha。所以,我决定手动输入captcha使用javascript对话框弹出。但是我的代码的问题在于,为了成功实现,它使用wait并在wait()之后自动接受警告框。而且,如果我按输入验证码后输入,这个错误被抛出在Selenium Python上处理javascript对话框
selenium.common.exceptions.UnexpectedAlertPresentException
这里是我的代码 -
def captcha():
driver.execute_script("var a = prompt('Enter Captcha', '');document.body.setAttribute('data-id', a)")
time.sleep(7)
driver.switch_to.alert.accept()
driver.find_element_by_id("captcha_code").send_keys(driver.find_element_by_tag_name('body').get_attribute('data-id'))
driver.find_element_by_id("captcha_code").send_keys(Keys.RETURN)
提高IT我试过这个代码,其中一个while循环正在检查是否存在Alert框,但它不起作用。
def captcha():
driver.execute_script("var a = prompt('Enter Captcha', '');document.body.setAttribute('data-id', a)")
while EC.alert_is_present():
time.sleep(1)
print("Alert Present")
try:
driver.switch_to.alert.accept()
except selenium.common.exceptions.NoAlertPresentException:
print("Error Encountered...")
continue
driver.find_element_by_id("captcha_code").send_keys(driver.find_element_by_tag_name('body').get_attribute('data-id'))
driver.find_element_by_id("captcha_code").send_keys(Keys.RETURN)
它始终打印 -
警报目前
并继续打印此,即使我没有存在提醒框很长一段时间。
任何帮助,将不胜感激。提前致谢。
答
变化
while EC.alert_is_present():
要
while EC.alert_is_present()(driver) :
EC.alert_is_present()
返回功能,因此将您在使用Chrome或Firefox始终为true
+0
感谢它现在工作正常。 :) –
? –
我正在使用Chrome Webdriver。 –