selenium技巧 - 通过js来控制滚动条,通过xpath定位最上层的div层

来源:互联网 发布:威海博优化纤怎么样 编辑:程序博客网 时间:2024/06/06 13:18
业务流程:

1.打开此网页 http://nanjing.xiaomishu.com/shop/search/sp2048_745
2.向下拖动滚动条,右下角自动会出现【投诉与建议】(此网页已经修改不拖动也出现了,以前是没有的,)
3.点击【投诉与建议】
4.在打开的div 层中输入姓名,邮件,内容 并点击确定
5.验证页面上的提示文字






package com.example.tests;import org.junit.*;import org.openqa.selenium.*;import org.openqa.selenium.ie.InternetExplorerDriver;public class SeleniumWebDriver {public static WebDriver driver;@Testpublic void testUnit() {driver = new InternetExplorerDriver();driver.get("http://nanjing.xiaomishu.com/shop/search/sp2048_745");maxBrowser(driver);setScroll(driver,500);driver.findElement(By.linkText("投诉与建议")).click();driver.findElement(By.xpath("//input[@id='repName']")).sendKeys("1");driver.findElement(By.xpath("//input[@id='repMail']")).sendKeys("1");driver.findElement(By.xpath("//textarea[@id='repContent']")).sendKeys("hello");driver.findElement(By.xpath("//a[@id='repBtn']")).click();Assert.assertEquals("您输入的邮箱格式不正确", driver.findElement(By.xpath("//div[@id='floatBox_remind']/span")).getText());}//将IE最大化public static void  maxBrowser(WebDriver driver){try {String maxBroswer = "if (window.screen) {window.moveTo(0, 0);" +"window.resizeTo(window.screen.availWidth,window.screen.availHeight);}";JavascriptExecutor jse=(JavascriptExecutor) driver;jse.executeScript(maxBroswer);} catch (Exception e) {System.out.println("Fail to  Maximization browser");}}//将滚动条滚到适合的位置public static void setScroll(WebDriver driver,int height){try {String setscroll = "document.documentElement.scrollTop=" + height;JavascriptExecutor jse=(JavascriptExecutor) driver;jse.executeScript(setscroll);} catch (Exception e) {System.out.println("Fail to set the scroll.");}}}

对于这种顶级div层,一开始用id来定位,在firefox中可以正常跑
在IE中会报stack overflow的错误,一直以来是以为没有加等待时间而没找到
后来试了很多方法,最后发现用xpath就解决了,真是耽误了很久的时间
给大家借鉴,如果一个定位方法不能用时,多换换其他的

这个例子中我们学习了如何用JS控制滚动条,如何最大化IE页面。

原创粉丝点击