selenium中使用JS处理页面滚动条

selenium+Java使用JS处理页面滚动条

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

public class test {
     

	public static void main(String[] args) throws InterruptedException {
     
		// 启动浏览器进入相应网页
		System.setProperty("webdriver.chrome.driver", "webdriver/chromedriver.exe");
		WebDriver driver = new ChromeDriver();
		driver.manage().window().maximize();
		driver.get("https://blog.csdn.net/weixin_44169484");
		Thread.sleep(1000);
		
        // 定位元素
		WebElement element = driver.findElement(By.xpath(".//*[@id='seeOriginal']/label"));
		JavascriptExecutor JS = (JavascriptExecutor)driver;
		// 移动到元素element对象的“顶端”与当前窗口的“顶部”对齐
		JS.executeScript("arguments[0].scrollIntoView();", element);
		// 移动到元素element对象的“底端”与当前窗口的“底部”对齐
		JS.executeScript("arguments[0].scrollIntoView(false);", element);
		Thread.sleep(2000);
		// 移动到元素element对象的“顶端”与当前窗口的“顶部”对齐
		JS.executeScript("arguments[0].scrollIntoView(true);", element);
		Thread.sleep(2000);
		// 将页面滚动条拖到底部
		JS.executeScript("window.scrollTo(0,document.body.scrollHeight)");
		Thread.sleep(2000);
		// 将滚动条向上拉到顶
        JS.executeScript("scrollTo(0,1)");
        Thread.sleep(2000);
		// 将滚动条向下拉到底
		JS.executeScript("scrollTo(0,100000)");
		Thread.sleep(2000);
		// 将滚动条拉到中间
		JS.executeScript("scrollBy(0, 0-document.body.scrollHeight *1/2)");
	    Thread.sleep(2000);
	    // 将左右滚动条拉到中间
	    JS.executeScript("scrollBy(0, 0-document.body.scrollWidht *1/2)");
	    Thread.sleep(2000);
		driver.quit();
    }
}

你可能感兴趣的:(Java自动化,selenium,java,chrome)