Chúng ta có thể cuộn trang web trong Selenium bằng Java. Selenium không xử lý cuộn trực tiếp. Nó nhờ Javascript Executor để thực hiện hành động cuộn đến một phần tử.
Trước hết, xác định phần tử cần cuộn đến. Tiếp theo, dùng Javascript Executor chạy lệnh JavaScript. Phương thức executeScript dùng để chạy JS trong Selenium. Ta dùng phương thức scrollIntoView trong JS và truyền true làm đối số.
Cú pháp:
WebElement elm = driver.findElement(By.name("name"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", elm);
Ví dụ
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollAction {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
// implicit wait
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
// launch application
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// xác định phần tử
WebElement n = driver.findElement(By.xpath("//*[text()='Contact']"));
// Javascript executor
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", n);
}
}
Kết quả
