Scroll Element into View with Selenium

前端 未结 30 2852
时光说笑
时光说笑 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条回答
  •  闹比i
    闹比i (楼主)
    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 +")");
    

提交回复
热议问题