program story

Java를 사용하여 Selenium WebDriver (Selenium 2)에서 페이지 스크롤 위 또는 아래

inputbox 2020. 12. 10. 19:56
반응형

Java를 사용하여 Selenium WebDriver (Selenium 2)에서 페이지 스크롤 위 또는 아래


Java를 사용하는 페이지 스크롤을 위해 Selenium 1 (일명 Selenium RC)에서 다음 코드를 작성했습니다.

selenium.getEval("scrollBy(0, 250)");

Selenium 2 (WebDriver)의 동등한 코드는 무엇입니까?


들어 아래로 스크롤 :

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("window.scrollBy(0,250)");

또는 다음과 같이 할 수 있습니다.

jse.executeScript("scroll(0, 250);");

대한 스크롤 :

jse.executeScript("window.scrollBy(0,-250)");
OR,
jse.executeScript("scroll(0, -250);");

페이지 하단으로 스크롤 :

JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

Selenium Webdriver에서 위아래로 스크롤하는 방법은 여러 가지가 있습니다. 저는 항상 Java Script를 사용하여 동일한 작업을 수행합니다.

아래는 위아래로 스크롤하려는 경우 항상 나를 위해 작동하는 코드입니다.

 // This  will scroll page 400 pixel vertical
  ((JavascriptExecutor)driver).executeScript("scroll(0,400)");

Selenium의 스크롤 페이지에서 전체 코드를 얻을 수 있습니다.

요소를 스크롤하려면 아래 코드가 작동합니다.

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

여기에서 전체 문서를 얻을 수 있습니다. 특정 요소 스크롤


이것은 귀하의 질문에 대한 정확한 답변이 아닐 수 있지만 (WebDriver 측면에서) java.awt라이브러리가 selenium.Keys. 따라서 전자를 사용하는 페이지 다운 작업은 다음과 같습니다.

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_PAGE_DOWN);
robot.keyRelease(KeyEvent.VK_PAGE_DOWN);

JavascriptExecutor js = ((JavascriptExecutor) driver);

아래로 스크롤:

js.executeScript("window.scrollTo(0, document.body.scrollHeight);");

스크롤:

js.executeScript("window.scrollTo(0, -document.body.scrollHeight);");

이 시도

        Actions dragger = new Actions(driver);
        WebElement draggablePartOfScrollbar = driver.findElement(By.xpath("//*[@id='jobreslist_outercontainer']/div/div[2]/div"));

        // drag downwards
        int numberOfPixelsToDragTheScrollbarDown = 50;
        for (int i=10;i<500;i=i+numberOfPixelsToDragTheScrollbarDown){
            try{
        // this causes a gradual drag of the scroll bar, 10 units at a time
        dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0,numberOfPixelsToDragTheScrollbarDown).release().perform();
        Thread.sleep(1000L);
            }catch(Exception e1){}
        } 

        // now drag opposite way (downwards)
        numberOfPixelsToDragTheScrollbarDown = -50;
        for (int i=500;i>10;i=i+numberOfPixelsToDragTheScrollbarDown){
        // this causes a gradual drag of the scroll bar, -10 units at a time
        dragger.moveToElement(draggablePartOfScrollbar).clickAndHold().moveByOffset(0,numberOfPixelsToDragTheScrollbarDown).release().perform();
        Thread.sleep(1000L);
        }

JavaScript 또는 외부 라이브러리를 사용하고 싶지 않았으므로 이것이 내 솔루션 (C #)이었습니다.

IWebElement body = Driver.FindElement(By.TagName("body"));

IAction scrollDown = new Actions(Driver)
    .MoveToElement(body, body.Size.Width - 10, 15) // position mouse over scrollbar
    .ClickAndHold()
    .MoveByOffset(0, 50) // scroll down
    .Release()
    .Build();

scrollDown.Perform();

또한 모든 요소에서 위아래로 스크롤하는 확장 메서드로 쉽게 만들 수 있습니다.


를 사용하여 모든 요소를 ​​선택하려면 페이지에 스크롤을 추가해야합니다 Selenium.executeScript("window.scrollBy(0,450)", "").

목록이 큰 경우 실행을 통해 스크롤을 여러 번 추가하십시오. 스크롤은 페이지의 특정 지점 (예 : 0,450)으로 만 이동합니다.


JavascriptExecutor jse = ((JavascriptExecutor) driver);
jse.executeScript("window.scrollTo(0, document.body.scrollHeight)");

이 코드는 저에게 효과적입니다. 테스트중인 페이지는 아래로 스크롤하면로드됩니다.


Javascript executor는 항상 작업을 완벽하게 수행합니다.

((JavascriptExecutor) driver).executeScript("scroll(0,300)");

where (0,300) are the horizontal and vertical distances respectively. Put your distances as per your requirements.

If you a perfectionist and like to get the exact distance you like to scroll up to on the first attempt, use this tool, MeasureIt. It's a brilliant firefox add-on.


Thanks for Ripon Al Wasim's answer. I did some improvement. because of network problems, I retry three times until break loop.

driver.get(url)
# Get scroll height
last_height = driver.execute_script("return document.body.scrollHeight")
try_times = 0
while True:
    # Scroll down to bottom
    driver.execute_script("window.scrollBy(0,2000)")

    # Wait to load page
    time.sleep(scroll_delay)
    # Calculate new scroll height and compare with last scroll height
    new_height = driver.execute_script("return document.body.scrollHeight")

    if last_height == new_height:
        try_times += 1

    if try_times > 3:
        try_times = 0
        break
    last_height = new_height

  1. If you want to scroll the page vertically to perform some action, you can do it using the following JavaScript. ((JavascriptExecutor)driver).executeScript(“window.scrollTo(0, document.body.scrollHeight)”);

        Where ‘JavascriptExecutor’ is an interface, which helps executing JavaScript through Selenium WebDriver. You can use the following code to import.
    

import org.openqa.selenium.JavascriptExecutor;

2.If you want to scroll at a particular element, you need to use the following JavaScript.

WebElement element = driver.findElement(By.xpath(“//input [@id=’email’]”));((JavascriptExecutor) driver).executeScript(“arguments[0].scrollIntoView();”, element);

Where ‘element’ is the locator where you want to scroll.

3.If you want to scroll at a particular coordinate, use the following JavaScript.
((JavascriptExecutor)driver).executeScript(“window.scrollBy(200,300)”); Where ‘200,300’ are the coordinates.

4.If you want to scroll up in a vertical direction, you can use the following JavaScript. ((JavascriptExecutor) driver).executeScript(“window.scrollTo(document.body.scrollHeight,0)”);

  1. If you want to scroll horizontally in the right direction, use the following JavaScript. ((JavascriptExecutor)driver).executeScript(“window.scrollBy(2000,0)”);

  2. If you want to scroll horizontally in the left direction, use the following JavaScript. ((JavascriptExecutor)driver).executeScript(“window.scrollBy(-2000,0)”);

참고URL : https://stackoverflow.com/questions/12293158/page-scroll-up-or-down-in-selenium-webdriver-selenium-2-using-java

반응형