2014 from—http://blog.csdn.net/tanzhangwen/article/details/18733557
这里面主要由链接(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执行脚本直接滚动到指定坐标位置(LinkLink2)
- 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();
发现最新的webdriver代码已改,上面的函数已经没有了,经过试验一下代码可以替换:
- Coordinates coor = ((Locatable)element).getCoordinates();
- coor.inViewPort();