Selenium WebDriver ไม่มีคำสั่ง scroll ตรงๆ ต้องใช้ JavascriptExecutor เพื่อรัน JavaScript คำสั่ง scrollIntoView() แทน
Syntax
WebElement element = driver.findElement(By.locator("value"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
scrollIntoView(true)- scroll จน element อยู่บนสุดของ viewportscrollIntoView(false)- scroll จน element อยู่ล่างสุดของ viewport
ตัวอย่างโค้ดสมบูรณ์
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class ScrollDownExample {
public static void main(String[] args) {
// ตั้งค่า ChromeDriver path
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
try {
// เปิดหน้าเว็บ
driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
// หา element ที่ต้องการ scroll ไป (เช่น element ที่มีข้อความ "Contact")
WebElement contactElement = driver.findElement(
By.xpath("//*[text()='Contact']"));
// Scroll ไปยัง element นั้น
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView(true);", contactElement);
// หยุดสักครู่เพื่อดูผลลัพธ์
Thread.sleep(2000);
System.out.println("Scrolled to Contact element successfully");
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
วิธี Scroll อื่นๆ ที่ใช้บ่อย
1. Scroll ลงตามพิกัด ( 픽เซล)
// Scroll ลง 500 pixel
((JavascriptExecutor) driver).executeScript("window.scrollBy(0, 500);");
2. Scroll ไปยังตำแหน่งเฉพาะ
// Scroll ไปยังตำแหน่ง y = 1000
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, 1000);");
3. Scroll จนถึงท้ายหน้า
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight);");
4. Scroll element เฉพาะ (เช่น div ที่มี scrollbar)
WebElement scrollableDiv = driver.findElement(By.cssSelector(".scroll-container"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollTop = arguments[0].scrollHeight;", scrollableDiv);
Best Practices
- ใช้
WebDriverWaitรอ element แทนThread.sleep() - ตรวจสอบว่า element มองเห็นได้จริงด้วย
element.isDisplayed() - ใช้
scrollIntoView({behavior: 'smooth'})สำหรับ smooth scroll (รองรับบราวเซอร์ใหม่ๆ)
ตัวอย่างกับ Explicit Wait
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;
// ... setup driver ...
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.xpath("//*[text()='Contact']")));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", element);