เราสามารถเลื่อนหน้าเว็บใน Selenium โดยใช้ Java ซีลีเนียมไม่สามารถจัดการการเลื่อนได้โดยตรง ต้องใช้ความช่วยเหลือจาก Javascript Executor เพื่อดำเนินการเลื่อนขึ้นไปยังองค์ประกอบ
ก่อนอื่น เราต้องค้นหาองค์ประกอบที่เราต้องเลื่อน ต่อไป เราจะใช้ Javascript Executor เพื่อรันคำสั่ง Javascript เมธอด executeScript ใช้เพื่อรันคำสั่ง Javascript ใน Selenium เราจะใช้เมธอด scrollIntoView ใน Javascript และส่งผ่าน true เป็นอาร์กิวเมนต์ของเมธอด
ไวยากรณ์ −
WebElement elm = driver.findElement(By.name("name"));
((JavascriptExecutor) driver)
.executeScript("arguments[0].scrollIntoView(true);", elm); ตัวอย่าง
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 ");
// identify element
WebElement n=driver.findElement(By.xpath("//*[text()='Contact']"));
// Javascript executor
((JavascriptExecutor)driver)
.executeScript("arguments[0].scrollIntoView(true);", n);
}
} ผลลัพธ์
