如何使用 Selenium 中的 Actions 类向上/向下滚动页面?
我们可以使用 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(); } }
输出
广告