How to scroll to element with Selenium WebDriver u

2019-02-12 02:09发布

How do I get Selenium WebDriver to scroll to a particular element to get it on the screen. I have tried a lot of different options but have had no luck. Does this not work in the c# bindings?

I can make it jump to a particular location ex ((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollTo(0, document.body.scrollHeight - 150)"); But I want to be able to send it to different elements without giving the exact location each time.

public IWebElement Example { get { return Driver.FindElement(By.Id("123456")); } }

Ex 1) ((IJavaScriptExecutor)Driver).ExecuteScript("arguments[0].scrollIntoView(true);", Example);

Ex 2) ((IJavaScriptExecutor)Driver).ExecuteScript("window.scrollBy(Example.Location.X", "Example.Location.Y - 100)");

When I watch it, it does not jump down the page to the element, and the exception matches the element being off screen.

Update: I added an bool ex = Example.Exists(); after it and checked the results. It does Exist (its true). Its not Displayed (as its still offscreen as it has not moved to the element) Its not Selected ??????

Someone is seeing success By.ClassName. Does anyone know if there is a problem with doing this By.Id in the c# bindings?

4条回答
Juvenile、少年°
2楼-- · 2019-02-12 02:23

Its little older question, but I believe that there is better solution than suggested above.

Here is original answer: https://stackoverflow.com/a/26461431/1221512

You should use Actions class to perform scrolling to element.

var element = driver.FindElement(By.id("element-id"));
Actions actions = new Actions(driver);
actions.MoveToElement(element);
actions.Perform();
查看更多
我只想做你的唯一
3楼-- · 2019-02-12 02:24

For scroll down inside the page here I have small code and solution

My Scenario was until I scroll down the page. Accept and Don't accept button was not getting enabled. I was having 15 terms and conditions from which I needed to select 15th term and condition by inspecting webpage and taking the Id of last terms and condition paragraph.

driver.FindElement(By.Id("para15")).Click();

<div id="para15">One way Non-Disclosure Agreement</div>
查看更多
不美不萌又怎样
4楼-- · 2019-02-12 02:31

This works for me:

var elem = driver.FindElement(By.ClassName("something"));
driver.ExecuteScript("arguments[0].scrollIntoView(true);", elem);
查看更多
Melony?
5楼-- · 2019-02-12 02:41

This works for me in Chrome, IE8 & IE11:

public void ScrollTo(int xPosition = 0, int yPosition = 0)
{
    var js = String.Format("window.scrollTo({0}, {1})", xPosition, yPosition);
    JavaScriptExecutor.ExecuteScript(js);
}

public IWebElement ScrollToView(By selector)
{
    var element = WebDriver.FindElement(selector);
    ScrollToView(element);
    return element;
}

public void ScrollToView(IWebElement element)
{
    if (element.Location.Y > 200)
    {
        ScrollTo(0, element.Location.Y - 100); // Make sure element is in the view but below the top navigation pane
    }

}
查看更多
登录 后发表回答