有时候我们需要对窗口显示的页面上下滑动,以显示当前正在处理的位置,这就需要用到webdriver模拟鼠标上下滑动
package test20161201; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; public class test20161201 { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver", "C:\Training\Automation\Software\drivers\chromedriver_win32\chromedriver.exe");和上面一行是连着的 WebDriver driver= new ChromeDriver(); driver.navigate().to("http://www.baidu.com"); System.out.println("打开浏览器进入百度首页"); driver.manage().window().maximize(); System.out.println("窗口最大化"); Thread.sleep(2000); driver.manage().window().setSize(new Dimension(800, 200));----------------浏览器窗口大小改变 Thread.sleep(1000); driver.manage().window().setSize(new Dimension(200, 800)); Thread.sleep(1000); driver.manage().window().setSize(new Dimension(600, 600)); Thread.sleep(1000); driver.manage().window().maximize(); System.out.println("最后将窗口最大化"); Thread.sleep(1000); driver.findElement(By.id("kw")).sendKeys("知乎"); driver.findElement(By.id("su")).click(); Thread.sleep(3000); WebElement content = driver.findElement(By.xpath("//*[@id='1']/div[1]/div[2]/div[1]")); System.out.println(content);//这里定义了一个变量content driver.findElement(By.linkText("知乎- 与世界分享你的知识、经验和见解")).click(); System.out.println("进入知乎首页"); Thread.sleep(5000); for(String winHandle:driver.getWindowHandles()){ driver.switchTo().window(winHandle); } driver.close(); Thread.sleep(2000); for(String winHandle:driver.getWindowHandles()){ driver.switchTo().window(winHandle); } Thread.sleep(2000); Actions action = new Actions(driver);-------------------------------------------声明一个动作 WebElement xia = driver.findElement(By.xpath("//*[@id='help']/a[3]"));----------找到向下滑动到的元素位置 action.moveToElement(xia).build().perform();------------------------------------执行滑动动作 Thread.sleep(1000); WebElement shang = driver.findElement(By.xpath("//*[@id='container']/div[2]/div/div[2]/div"));----------找到向上滑动到的元素位置
action.moveToElement(shang).build().perform();----------------------------------执行滑动动作
System.out.println("鼠标下拉结束");