Selenium:使用Actions类的水平滚动

时间:2017-10-31 11:49:00

标签: selenium selenium-webdriver scrollbar action mcustomscrollbar

我已尝试通过Selenium操作以及Javascript Executor在我的网页上访问此自定义滚动条。滚动条仅滚动500像素,实际上我希望它在整个宽度上滚动。任何帮助表示赞赏。以下是我目前的代码段:

 WebElement slider = element("slider_div");
 WebElement scrollbar = element("scrollbar");
 int w = slider.getSize().getWidth();
 Actions move = new Actions(driver);
 move.dragAndDropBy(e, offset, 0).build() .perform();

我也尝试过以下解决方案,但仍然无法解决问题:

WebElement slider = element("slider_div");
WebElement scrollbar = element("scrollbar");
int w = slider.getSize().getWidth();
clickByJavascript(slider);
Actions action = new Actions(driver); 
action.sendKeys(Keys.RIGHT).build().perform();`

提前致谢!!!

2 个答案:

答案 0 :(得分:2)

我已经在下面指定的网站上测试了你的情节,水平和垂直滚动。

测试网址« https://trello.com/b/LakLkQBW/jsfiddle-roadmap ;

  

元素内部垂直滚动«

  • Selenium java:

    WebElement element = driver.findElement(By.xpath("//div[@id='board']/div[1]/div[1]/div[2]") );
    for (int i = 0; i < 5; i++) {
        jse.executeScript("arguments[0].scrollTop += 200;", element);
    }
    
  • javascript | jquery:

    var objDiv = $x("//div[@id='board']/div[1]/div[1]/div[2]")[0];
    console.log( objDiv );
    
    objDiv.scrollTop += 100; 
    //objDiv.scrollTop = objDiv.scrollHeight;
    
  

元素内部水平滚动«

  • Java Actions Class

    WebElement horizontalbar = driver.findElement(By.id("board") );
    Actions action = new Actions(driver);
    
    Actions moveToElement = action.moveToElement( horizontalbar );
    for (int i = 0; i < 5; i++) {
        moveToElement.sendKeys(Keys.RIGHT).build().perform();
    }
    
  

滚动,直到元素进入视图。

  • JavaScript的

    public void scroll_Till_Element(String id) {
        WebElement element = driver.findElement(By.id( id ) );
        jse.executeScript("arguments[0].scrollIntoView(true);", element);
    }
    
  

滚动到页面末尾。

public void scrollPage() throws InterruptedException {
    driver.get("https://stackoverflow.com/q/33094727/5081877");

    Actions actions = new Actions(driver);
    WebElement element = driver.findElement(By.xpath("//body") );
    Actions scrollDown = actions.moveToElement( element );
    scrollDown.keyDown(Keys.CONTROL).sendKeys(Keys.END).build().perform();
    //jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");

    Thread.sleep( 1000 * 4 );

    /*Actions scrollUP = actions.moveToElement( element );
    scrollUP.keyDown(Keys.CONTROL).sendKeys(Keys.HOME).build().perform();*/
    jse.executeScript("window.scrollTo(0, -document.body.scrollHeight)");

    scroll_Till_Element( "answer-33142037" );
}

对于javascript,您可以使用其中任何一种。

window.scrollBy(0,800);
window.scrollTo(0, -document.body.scrollHeight);
scroll(0, -document.body.scrollHeight);

@see

答案 1 :(得分:0)

使用以下线条从左向右滚动

((JavascriptExecutor) driver).executeScript("window.scrollBy(500000, 0)");

要从右向左滚动,请使用以下行:

((JavascriptExecutor) driver).executeScript("window.scrollBy(-500000, 0)");

这将完全向左或向右滚动,因为(50000)是一个非常大的值来覆盖页面