彈出框處理,這裏介紹兩種方法
使用的alert.html放置在E:\demo\alert.html目錄,源代碼:
<!DOCTYPE html PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
<head>
<title>Alert Test</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
</head>
<body>
<h2>Alert Test</h2>
<script type="text/javascript">
function showAlert(){
alert(document.f1.t1.value);
}
function showMultilineAlert(){
alert("You must correct the following Errors:\nYou must select a messaging price plan.\nYou must select an international messaging price plan.\nYou must enter a value for the Network Lookup Charge");
}
function showMultiUnicode(){
alert("Verifique se todos os campos obrigatórios foram preenchidos.\n\nProduto:required.");
}
</script>
<form name="f1">
<input type="text" name="t1" value="Alert Message"><br><br>
<input type="button" name="b1" value="Click For Alert" onclick="showAlert()"><br>
<input type="button" name="b2" value="Click For Multiline Alert" onclick="showMultilineAlert()"><br>
<input type="button" name="b3" value="Multiline Unicode" onclick="showMultiUnicode()"><br>
</form>
</body>
</html>
方法1,使用switch_to_alert()方法:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("file:///E:/demo/alert.html")
driver.find_element_by_name("b1").click()
#切換到alert彈出框
alert = driver.switch_to_alert()
#打印警告框文本信息
print("-----------------alert彈出框顯示信息--------------------",alert.text)
#接受警告框
alert.accept()
driver.quit()
方法2,使用switch_to.alert方法
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("file:///E:/demo/alert.html")
driver.find_element_by_name("b2").click
#切換到alert提示框
alert = driver.switch_to.alert()
#輸出提示框文本信息
print("----------------------------",alert.text)
#解散提示框
alert.dismiss()
driver.quit()