使用 Selenium 将元素滚动到视图中。
我们可能需要对页面可视区域中不存在的元素执行操作。我们需要向下滚动页面以到达该元素。
Selenium 无法直接执行滚动操作。这可以通过 Javascript 执行器 和 Selenium 中的动作类 来实现。DOM 可以借助 Javascript 操作网页上的所有元素。
Selenium 可以借助 **execute_script()** 方法执行 Javascript 中的命令。对于 Javascript 解决方案,我们必须将 true 值传递给 **scrollIntoView()** 方法以识别页面上我们当前位置下方的对象。我们可以借助 Selenium 中的动作类执行鼠标移动。
示例
使用 Javascript 执行器的代码实现。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.JavascriptExecutor;
public class ScrollToViewJs{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// identify element
WebElement l=driver.findElement(By.xpath("//*[text()='ABOUT US']"));
// Javascript executor
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", l);
Thread.sleep(800);
driver.quit();
}
}在使用动作类滚动到视图时,我们必须使用 moveToElement() 方法。此方法将执行鼠标移动,直到元素的中间位置。
示例
使用动作类的代码实现。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class ScrollToViewActions{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String url = "https://tutorialspoint.com/index.htm";
driver.get(url);
driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
// identify element
WebElement l=driver.findElement(By.xpath("//*[text()='ABOUT US']"));
// Actions class with moveToElement()
Actions a = new Actions(driver);
a.moveToElement(l);
a.perform();
driver.quit();
}
}输出

广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP