Scroll Element into View with Selenium

Is there any way in either Selenium 1.x or 2.x to scroll the browser window so that a particular element identified by an XPath is in view of the browser? There is a focus method in Selenium, but it does not seem to physically scroll the view in FireFox. Does anyone have any suggestions on how to do this?

The reason I need this is I'm testing the click of an element on the page. Unfortunately the event doesn't seem to work unless the element is visible. I don't have control of the code that fires when the element is clicked, so I can't debug or make modifications to it, so, easiest solution, scroll the item into view.


Have tried many things with respect to scroll, but the below code has provided better results.

This will scroll until the element is in view :

WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500); 

//do anything you want with the element

您可以使用org.openqa.selenium.interactions.Actions类来移动到一个元素:

WebElement element = driver.findElement(By.id("my-id"));
Actions actions = new Actions(driver);
actions.moveToElement(element);
actions.perform();

JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("javascript:window.scrollBy(250,350)");

你可能想试试这个。

链接地址: http://www.djcxy.com/p/65328.html

上一篇: 使用Selenium进行浏览器插件测试

下一篇: 使用硒将元素滚动到视图中