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

Python脚本控制的WebDriver 常用操作 <二十三> wait

2013-12-18 21:59 609 查看

测试用例场景

  Wait类的使用场景是在页面上进行某些操作,然后页面上就会出现或隐藏一些元素,此时使用Wait类的until方法来等待这些效果完成以便进行后续的操作。另外页面加载时有可能会执行一些ajax,这时候也需要去WebDriverWait的until的等待ajax的请求执行完毕。

  具体一点的例子前面也曾出现过,点击一个链接然后会出现一个下拉菜单,此时需要先等待下拉菜单出现方可进行点击菜单项的操作。

  这时候就需要用到selenium.webdriver.support.ui.WebDriverWait类,实例化该类时可以传入timeout的时间,单位是 s。

  until方法会一直等下去,直到

代码块中的内容为true(不为false或没有抛出异常)

超时,也就是超过了timeout设置的时间

Python脚本

测试用HTML脚本:

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<title>wait</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(){
$('#btn').click(function(){
$('<p><span class="label label-info">waitr-webdriver</span></p>').css('margin-top', '1em').insertAfter($(this));
$(this).addClass('disabled').unbind('click');
});
});
</script>
</head>

<body>
<div class="row-fluid">
<div class="span6 well">
<h3>wait</h3>
<button class="btn btn-primary" id="btn" >Click</button>
</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月18日

@author: Administrator
'''
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.keys import Keys
import os
import selenium.webdriver.support.ui as ui

dr = webdriver.Firefox()
file_path = 'file:///' +os.path.abspath('wait.html')
dr.get(file_path)

dr.find_element_by_id('btn').click()

wait = ui.WebDriverWait(dr, 10)
wait.until(lambda dr: dr.find_element_by_class_name('label').is_displayed())

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