Scroll Element into View with Selenium

前端 未结 30 2316
时光说笑
时光说笑 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:18

    In most of the situation for scrolling this code will work.

    WebElement element = driver.findElement(By.xpath("xpath_Of_Element"));                 
    js.executeScript("arguments[0].click();",element);
    
    0 讨论(0)
  • 2020-11-22 09:20
    JavascriptExecutor js = (JavascriptExecutor) driver;
            js.executeScript("javascript:window.scrollBy(250,350)");
    

    You may want to try this.

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

    JAVA

    Try scroll to element utilize x y position, and use JavascriptExecutor with this is argument: "window.scrollBy(x, y)".

    Following import:

    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.JavascriptExecutor;
    

    First you need get x y location the element.

    //initialize element
    WebElement element = driver.findElement(By.id("..."));
    
    //get position
    int x = element.getLocation().getX();
    int y = element.getLocation().getY();
    
    //scroll to x y 
    JavascriptExecutor js = (JavascriptExecutor) driver;
    js.executeScript("window.scrollBy(" +x +", " +y +")");
    
    0 讨论(0)
  • 2020-11-22 09:21

    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
    
    0 讨论(0)
  • 2020-11-22 09:21
    def scrollToElement(element: WebElement) = {
      val location = element.getLocation
      driver.asInstanceOf[JavascriptExecutor].executeScript(s"window.scrollTo(${location.getX},${location.getY});")
    }
    
    0 讨论(0)
  • 2020-11-22 09:21

    I am not sure if the question is still relevant but after referring to scrollIntoView documentation from https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView.

    The easiest solution would be

    executor.executeScript("arguments[0].scrollIntoView({block: \"center\",inline: \"center\",behavior: \"smooth\"});",element);
    

    This scrolls the element into center of the page.

    0 讨论(0)
提交回复
热议问题