1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > WebDriver中页面滚动(scrolling)

WebDriver中页面滚动(scrolling)

时间:2018-11-21 09:24:17

相关推荐

WebDriver中页面滚动(scrolling)

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

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

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

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

public static void test1() throws InterruptedException{WebDriver driver = new FirefoxDriver();driver.get("/");((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();

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。