未經做者容許,禁止轉載!!!java
java selenium webdriver處理JS操做窗口滾動條web
java selenium webdriver處理JS操做窗口滾動條chrome
import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class JS20161212 { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub System.setProperty("webdriver.chrome.driver","C:\\Training\\Automation\\Software\\drivers\\chromedriver_win32\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("https://www.hao123.com/"); driver.manage().window().maximize(); Thread.sleep(2000); JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("scrollTo(0,10000)");----------------------------------------------向下拉到底 Thread.sleep(2000); js.executeScript("scrollBy(0, 0-document.body.scrollHeight *99/100)");--------------向上拉到頂 Thread.sleep(2000); js.executeScript("scrollTo(0,100000)");---------------------------------------------向下拉到底 Thread.sleep(2000); js.executeScript("scrollTo(0,1)");--------------------------------------------------向上拉到頂 Thread.sleep(2000); js.executeScript("scrollTo(0,1000)"); 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)");------------------左右拉到中間
精簡後的代碼 // ((JavascriptExecutor)driver).executeScript("scrollTo(0,10000)");----------------向下拉到底 // Thread.sleep(2000); // ((JavascriptExecutor)driver).executeScript("scrollTo(0,1)");--------------------向上拉到頂
// Thread.sleep(2000);
// ((JavascriptExecutor)driver).executeScript("document.documentElement.scrollTop=10000"); 將頁面滾動條拖到底部
// Thread.sleep(2000);
// ((JavascriptExecutor)driver).executeScript("document.documentElement.scrollTop=0"); 將頁面滾動條拖到頂部
// Thread.sleep(2000);
// } }
java selenium webdriver處理JS操做窗口滾動條spa