您的位置:首页 > 编程语言 > Python开发

Python脚本控制的WebDriver 常用操作 <十六> 处理对话框

2013-12-15 21:15 615 查看
下面将使用webdriver来处理一些页面跳出的对话框事件

测试用例场景

  页面上弹出的对话框是自动化测试经常会遇到的一个问题。前端框架的对话框经常是div形式的,下面是一些常见的对话框操作事件:

打开对话框

关闭对话框

操作对话框中的元素

Python脚本

测试用HTML代码:

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>Dialog</title>
<script type="text/javascript" async="" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" />
<script type="text/javascript">
$(document).ready(function(){
$('#click').click(function(){
$(this).parent().find('p').text('try Python-webdriver right now!');
});
});
</script>
</head>

<body>
<h3>Dialog</h3>
<div class="row-fluid">
<div class="span6">
<!-- Button to trigger modal -->
<a href="#myModal" role="button" class="btn btn-primary" data-toggle="modal" id="show_modal">Click</a>

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">X</button>
<h3 id="myModalLabel">Dialog header</h3>
</div>
<div class="modal-body">
<p>python-webdriver is better than slenium-webdriver</p>
<a href="#" id="click">click me</a>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</body>
<script src="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>
</html>


测试用Python代码:

# coding=gbk
'''
Created on 2013年12月15日

@author: Administrator
'''
from selenium import webdriver
from time import sleep
import os
import selenium.webdriver.support.ui as ui
if 'HTTP_PROXY' in os.environ: del os.environ['HTTP_PROXY']

#打开本地测试用html文件
dr = webdriver.Firefox()
file_path = 'file:///' + os.path.abspath('dialog.html')
dr.get(file_path)

#找到触发对话事件的按钮->单击
dr.find_element_by_id('show_modal').click()

#等待对话框完全显示
wait = ui.WebDriverWait(dr, 10)
wait.until(lambda dr:dr.find_element_by_id('myModal').is_displayed())

link = dr.find_element_by_id('myModal').find_element_by_id('click')
dr.execute_script('$(arguments[0]).click()',link)
sleep(5)

buttons = dr.find_element_by_class_name('modal-footer').find_elements_by_tag_name('button')
buttons[1].click()

sleep(5)
dr.quit()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: