Selenium 实战到吹牛系列
PS:Selenium 处理 js 中 alert、confirm、prompt三种弹窗
alert 例子
HTML:
<!DOCTYPE html>
<html>
<head>
<title>try alert</title>
</head>
<body>
</body>
<script type="text/javascript">
var result = alert("alert 例子");
</script>
</html>
代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-07-15 16:12:33
# @Author : BenLam
# @Link : https://www.cnblogs.com/BenLam/
from selenium import webdriver
driver=webdriver.Firefox()
driver.get(r'alert.html')
alert = driver.switch_to.alert
print(alert.text)
# 确认
alert.accept()
# 取消
alert.dismiss()
driver.quit()
输出结果:
>>>alert 例子
>>>
confirm 例子
HTML:
<!DOCTYPE html>
<html>
<head>
<title>try confirm</title>
</head>
<body>
</body>
<script type="text/javascript">
var result = confirm("confirm 例子");
</script>
</html>
代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-07-15 16:12:33
# @Author : BenLam
# @Link : https://www.cnblogs.com/BenLam/
from selenium import webdriver
driver=webdriver.Firefox()
driver.get(r'confirm.html')
confirm = driver.switch_to.alert
print(confirm.text)
# 确认
confirm.accept()
# 取消
confirm.dismiss()
driver.quit()
输出结果:
>>>confirm 例子
>>>
confirm 例子
HTML:
<!DOCTYPE html>
<html>
<head>
<title>try prompt</title>
</head>
<body>
</body>
<script type="text/javascript">
var result = prompt("prompt 例子");
if (result !== null) {
alert('您好~,' + result);
}
</script>
</html>
代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2019-07-15 16:12:33
# @Author : BenLam
# @Link : https://www.cnblogs.com/BenLam/
from selenium import webdriver
driver=webdriver.Firefox()
driver.get(r'prompt.html')
prompt = driver.switch_to.alert
print(prompt.text)
# prompt 特殊性是带 text 文本输入框
# 可以用 send_keys 输入内容
alert.send_keys("Test msg~")
# 确认
prompt.accept()
# 取消
prompt.dismiss()
driver.quit()
输出结果:
>>>prompt 例子
>>>