JS控制滾動條的位置:
window.scrollTo(x,y);
豎向滾動條置頂 window.scrollTo(0,0);
豎向滾動條置底 window.scrollTo(0,document.body.scrollHeight)
JS控制TextArea滾動條自動滾動到最下部
document.getElementById('textarea').scrollTop = document.getElementById('textarea').scrollHeight
例子:
import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.TimeoutException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; /** * @author Hjianhui * JavaScript.java 2016-08-01 * */ public class testScroll{ public static void main(String[] args) { // TODO Auto-generated method stub //利用webdriver鍵入搜索關鍵字 WebDriver driver = new FirefoxDriver(); try{ driver.get("http://www.baidu.com"); JavascriptExecutor driver_js= (JavascriptExecutor) driver; //利用js代碼鍵入搜索關鍵字 driver_js.executeScript("document.getElementById(\"kw\").value=\"yeetrack\""); driver.findElement(By.id("su")).click(); //等待元素頁面加載 waitForElementToLoad(driver, 10, By.xpath(".//*[@id='1']/h3/a[1]")); //將頁面滾動條拖到底部 driver_js.executeScript("window.scrollTo(0,document.body.scrollHeight)"); //#將頁面滾動條拖到頂部 driver_js.executeScript("window.scrollTo(0,0)"); }catch (Exception e){ e.printStackTrace(); } driver.quit(); } /** * 在給定的時間內去查找元素,如果沒找到則超時,拋出異常 * */ public static void waitForElementToLoad(WebDriver driver, int timeOut, final By By) { try { (new WebDriverWait(driver, timeOut)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { WebElement element = driver.findElement(By); return element.isDisplayed(); } }); } catch (TimeoutException e) { Assert.fail("超時!! " + timeOut + " 秒之后還沒找到元素 [" + By + "]"); } } }
waitForElementToLoad()函數是為了保證頁面元素已加載完成,以便執行JS代碼
Python代碼
from selenium import webdriver from selenium.webdriver.support.wait import WebDriverWait driver = webdriver.Firefox() driver.get("http://www.baidu.com") driver.execute_script("document.getElementById(\"kw\").value=\"selenium\"") WebDriverWait(driver, 10).until(lambda driver : driver.find_element_by_xpath(".//*[@id='container']/div[2]/div/div[2]")) driver.execute_script("window.scrollTo(0,document.body.scrollHeight)") driver.quit()
