我正在使用python上使用selenium webdriver编写一个自动化代码。但是,在某个时刻,它要求验证码。因此,我决定使用JavaScript对话框手动输入CAPTCHA。但是我的代码的问题是,为了成功实施,它使用等待并在wait()之后自动接受警报框。而且,如果我在输入验证码后按ENTER,则会丢弃此错误
selenium.common.exceptions.unpectedalertPresentException
这是我的代码 -
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)
为了改进它,我尝试了此代码,其中a em 每秒检查警报框,但它不起作用。
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():
to
while EC.alert_is_present()(driver) :
EC.alert_is_present()
返回一个函数,因此它将始终评估为true