如何在 Java 中使用 Selenium WebDriver 滚动页面向上或向下?
我们可以使用 Java 在 Selenium webdriver 中滚动页面向上或向下。这需要使用 Actions 类。首先,我们必须创建此 Actions 类的对象,然后应用 sendKeys 方法。
现在,要向下滚动页面,我们必须将参数 Keys.PAGE_DOWN 传递给此方法。要再次向上滚动页面,我们必须将参数 Keys.PAGE_UP 传递给 sendKeys 方法。最后,我们必须使用 build 和 perform 方法来执行此操作。
语法 −
Actions a = new Actions(driver); //scroll down a page a.sendKeys(Keys.PAGE_DOWN).build().perform(); //scroll up a page a.sendKeys(Keys.PAGE_UP).build().perform();
示例
代码实现
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.Keys; import org.openqa.selenium.interactions.Action; import org.openqa.selenium.interactions.Actions; public class ScrollUpDownActions{ 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(5, TimeUnit.SECONDS); //URL launch driver.get("https://tutorialspoint.com/index.htm"); // object of Actions class to scroll up and down Actions at = new Actions(driver); at.sendKeys(Keys.PAGE_DOWN).build().perform(); //identify element on scroll down WebElement l = driver.findElement(By.linkText("Latest Courses")); String strn = l.getText(); System.out.println("Text obtained by scrolling down is :"+strn); at.sendKeys(Keys.PAGE_UP).build().perform(); //identify element on scroll up WebElement m = driver.findElement(By.tagName("h4")); String s = m.getText(); System.out.println("Text obtained by scrolling up is :"+s); driver.quit(); } }
输出
广告