selenium webdriver——JS滚动到最底部
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()