Selenium (Java) - page scrolling

Method a: Selenium in analog operation with the keyboard and Actions Keys, thereby controlling page scrolling.

Method 2: Using JavaScript to achieve page scrolling.

code show as below:

package com.ceres.demos;

import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;

public class scrollTest {
	public static void main(String[] args) throws InterruptedException {
		WebDriver driver = new ChromeDriver();
		driver.get("https://www.baidu.com/s?wd=window");
		Thread.sleep(2000);
		/*
		 * 方法一:利用Selenium里的Actions和Keys模拟键盘操作,从而控制页面滚动;
		 */
		Actions actions = new Actions(driver);
		actions.sendKeys(Keys.DOWN).perform();
		Thread.sleep(1000);
		actions.sendKeys(Keys.ARROW_DOWN).perform();
		Thread.sleep(1000);
		actions.sendKeys(Keys.PAGE_DOWN).perform();
		Thread.sleep(1000);
		actions.sendKeys(Keys.END).perform();
		Thread.sleep(1000);
		actions.sendKeys(Keys.HOME).perform();
		/*
		 * 方法二:利用JavaScript实现页面滚动;
		 * scrollTo滚动到指定位置;
		 * scrollBy指定滚动方向和滚动量;
		 */
		String js1 = "window.scrollTo(0,300);";
		((JavascriptExecutor) driver).executeScript(js1);
		Thread.sleep(1000);
		String js2 = "window.scrollBy(0,-200);";
		((JavascriptExecutor) driver).executeScript(js2);
		Thread.sleep(1000);
		/*
		 * 方法二补充:滚动到指定元素所在位置
		 */
		String js3 = "arguments[0].scrollIntoView();";
		WebElement element = driver.findElement(By.id("rs"));//定位目标元素
		((JavascriptExecutor) driver).executeScript(js3, element);
		
//		driver.quit();
	}

}

reference:

https://www.cnblogs.com/moonpool/p/5677029.html

https://blog.csdn.net/lssrain/article/details/80108320

HTML Gets the height width of the screen, the browser, the page

Published 37 original articles · won praise 47 · Views 100,000 +

Guess you like

Origin blog.csdn.net/u013378642/article/details/88675866