Scroll Element into View with Selenium

前端 未结 30 2315
时光说笑
时光说笑 2020-11-22 08:31

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 m

相关标签:
30条回答
  • 2020-11-22 09:06

    If nothing works, try this before clicking:

    public void mouseHoverJScript(WebElement HoverElement) {
    
        String mouseOverScript = "if(document.createEvent){var evObj = document.createEvent('MouseEvents');evObj.initEvent('mouseover', true, false); arguments[0].dispatchEvent(evObj);} else if(document.createEventObject) { arguments[0].fireEvent('onmouseover');}";
        ((JavascriptExecutor) driver).executeScript(mouseOverScript, HoverElement);
    }
    
    0 讨论(0)
  • 2020-11-22 09:08

    In Selenium we need to take the help of a JavaScript executor to scroll to an element or scroll the page:

    je.executeScript("arguments[0].scrollIntoView(true);", element);
    

    In the above statement element is the exact element where we need to scroll. I tried the above code, and it worked for me.

    I have a complete post and video on this:

    http://learn-automation.com/how-to-scroll-into-view-in-selenium-webdriver/

    0 讨论(0)
  • 2020-11-22 09:09

    This is a repeated solution with JavaScript, but with an added waiting for element.

    Otherwise ElementNotVisibleException may appear if some action on the element is being done.

    this.executeJavaScriptFunction("arguments[0].scrollIntoView(true);", elementToBeViewable);
    WebDriverWait wait = new WebDriverWait(getDriver(), 5);
    wait.until(ExpectedConditions.visibilityOf(elementToBeViewable));
    
    0 讨论(0)
  • 2020-11-22 09:09

    In Java we can scroll by using JavaScript, like in the following code:

    driver.getEval("var elm = window.document.getElementById('scrollDiv'); if (elm.scrollHeight > elm.clientHeight){elm.scrollTop = elm.scrollHeight;}");
    

    You can assign a desired value to the "elm.scrollTop" variable.

    0 讨论(0)
  • 2020-11-22 09:11

    A solution is:

    public void javascriptclick(String element)
    {
        WebElement webElement = driver.findElement(By.xpath(element));
        JavascriptExecutor js = (JavascriptExecutor) driver;
    
        js.executeScript("arguments[0].click();", webElement);
        System.out.println("javascriptclick" + " " + element);
    }
    
    0 讨论(0)
  • 2020-11-22 09:12

    Targeting any element and sending down keys (or up/left/right) seems to work also. I know this is a bit of a hack, but I'm not really into the idea of using JavaScript to solve the scrolling problem either.

    For example:

    WebElement.sendKeys(Keys.DOWN);
    
    0 讨论(0)
提交回复
热议问题