WebDriver中页面滚动(scrolling)

这里面主要由链接(http://selenium-tutorial.blogspot.sg/2013/02/scroll-page-webdriver.html)整理过来,主要回答了如何用webdriver来滚动页面,滚上滚下,滚到指定元素以及怎么识别滚动条等。

1.  利用selenium中的focus(locator)函数实现(Link)

@Test
public void testFocus() throws Exception {
	selenium.open("/");
	selenium.windowMaximize();
	selenium.type("q", "selenium wiki");
	selenium.click("btnG");
	//Waiting for an element
	for (int second = 0;; second++) {
		if (second >= 60) fail("timeout");
		try { 
			if (selenium.isElementPresent("link=Selenium Overview - Wiki - Liferay.com")) 
				break; 
			} catch (Exception e) {}
		Thread.sleep(1000);
		}
	//Set focus on element --then page will scroll down --focus will be on that element
	selenium.focus("link=Selenium Overview - Wiki - Liferay.com");
	//To capture a screenshot
	selenium.captureScreenshot("c:/naga/screenshot.png");
	Thread.sleep(10000);
}

2. 利用webdriver执行脚本直接滚动到指定坐标位置(Link Link2)

	public static void test1() throws InterruptedException{
	    WebDriver driver = new FirefoxDriver();
	    driver.get("http://www.nytimes.com/");
	    ((JavascriptExecutor)driver).executeScript("scrollTo(0,3000)");
	     Thread.sleep(5000L);
	}

((JavascriptExecutor) driver).executeScript("scroll(0,250);");  //-250
((JavascriptExecutor) driver).executeScript("scroll(250,0);");
((JavascriptExecutor) driver).executeScript("window.scrollBy(0,250)", "");
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView();" ,webElement);



3. 判断是否有滚动条可以比较窗口高度和滚动条高度(Link)

Selenium.type(xpath of the text-area element,text value);
String str1=Selenium.getEval("this.browserbot.getCurrentWindow().document.getElementsByClassName(‘cssclassname‘)[0].clientHeight");
String str = Selenium.getEval("this.browserbot.getCurrentWindow().document.getElementsByClassName(‘cssclassname‘)[0].scrollHeight");
int clientHeight = Integer.parseInt(str1);
int scrollHeight = Integer.parseInt(str);

if(clientHeight < scrollHeight){
	System.out.println("Vertical scrollbar appears");
}else{
	System.out.println("Vertical scrollbar is not appear");
}

4. 滚动到目标元素的纵坐标位置(Link)

public void scrollAndClick(By by)
{
   WebElement element = driver.findElement(by);
   int elementPosition = element.getLocation().getY();
   String js = String.format("window.scroll(0, %s)", elementPosition);
   ((JavascriptExecutor)driver).executeScript(js);
   element.click();
}

5. 滚动到指定元素位置

WebElement element = webdriver.findElement(locator);
((Locatable)element).getLocationOnScreenOnceScrolledIntoView();



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。