Selenium常用方法1

元素定位:Webdriver的findElment方法可以用来找到页面中的某个元素。下面简单介绍几种比较常用的方法。

By ID
我们知道页面上标签的id属性值是唯一的,所以定位到的元素也是唯一。

<input type="text" name="passwd" id="passwd-id" />
WebElement element = driver.findElement(By.id("passwd-id"));

By Name
通过标签的name属性值定位到目标元素,页面中name字段值可以重复,所以找到的目标元素可能会有多个

<input type="text" name="passwd"id="passwd-id" />
WebElement element = driver.findElement(By.name("passwd"));

By XPATH
更多关于xpath语法的学习链接网址

<input type="text" name="passwd"id="passwd-id" />
WebElement element =driver.findElement(By.xpath("//input[@id='passwd-id']"));

By Class Name
因为class的属性值可以重复,所以定位的元素可能会有多个。

<div 
class="cheese"><span>Cheddar</span></div><divclass="cheese"><span>Gouda</span></div>
List<WebElement>cheeses = driver.findElements(By.className("cheese")

By Link Text

通过连接的全部文本定位到目标元素

<ahref="http://www.google.com/search?q=cheese">cheese</a>
WebElement cheese =driver.findElement(By.linkText("cheese"));

等待除了可以让线程睡眠Thread.sleep()外;WebDriver还自带了一个只能等待的方法。

页面等待

因为Load页面的时候需要一段时间,如果页面还没有加载完就开始查找元素,那么结果必然是查找不到的。那么最好的方式就是设置一个默认的等待时间,在查找页面元素的时候如果找不到就等待一段时间再找,找到超时或者查到到目标元素。
显性等待:

new WebDriverWait(driver, 30).until(new ExpectedCondition<Boolean>() {
					public Boolean apply(WebDriver arg0) {
						WebElement text = arg0.findElement(By.id("*****"));
						if (text.getText().equals("") || text.getText() == null) {
							return false;
						}
						return true;
					}
				});

代码中:设置了等待时间为30s,在页面中查找id为newViewList的元素,如果没有找到就等待一段时间再找,WebDriverWait默认的每500毫秒调用一次ExpectedCondition()方法。


new WebDriverWait(driver, TIME_OUT_SECONDS).until(ExpectedConditions
						.visibilityOfElementLocated(By
								.id("****")));
				new WebDriverWait(driver, TIME_OUT_SECONDS).until(ExpectedConditions
						.invisibilityOfElementLocated(By
								.id("*****")));

.visibilityOfElementLocated:表示目标元素可见
.invisibilityOfElementLocated:表示目标元素不可见

调用Java Script
Web driver对Java Script的调用是通过JavascriptExecutor来实现的

((JavascriptExecutor) driver).executeScript(dateJs);

本章节内容摘抄于Selenium2.0使用文档
以上内容若出现有误或者表述不当的地方欢迎指正!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值