如何使用 Selenium 查找滚动位置?
我们可以使用 Selenium 来查找滚动位置。要查找位置,我们将使用 Javascript 执行器。我们必须验证浏览器中window.pageYOffset 的值。
URL 刚启动时,滚动在顶部,window.pageYOffset 的值为 0。当我们滚动到某个元素时,window.pageYOffset 的值会大于 0。
语法
JavascriptExecutor j = (JavascriptExecutor) driver; Long v = (Long) j.executeScript("return window.pageYOffset;");
示例
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 ScrollPosition{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://tutorialspoint.com/index.htm"); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // get current scroll position with Javascript Executor JavascriptExecutor j = (JavascriptExecutor) driver; Long v = (Long) j.executeScript("return window.pageYOffset;"); System.out.println("Scroll position after launch: " + v); // identify element WebElement n=driver.findElement(By.xpath("//*[text()='Careers']")); // Javascript executor to scroll to the element ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", n); Thread.sleep(200); // get current scroll position with Javascript Executor JavascriptExecutor js = (JavascriptExecutor) driver; double d = (double) js.executeScript("return window.pageYOffset;"); System.out.println("Scroll position after scrolling upto an element: "+d); driver.close(); } }
输出
广告