有時候我們需要控制頁面滾動條上的滾動條,但滾動條並非頁面上的元素,這個時候就需要借助js是來進行操作。一般用到操作滾動條的會兩個場景:
注冊時的法律條文需要閱讀,判斷用戶是否閱讀的標准是:滾動條是否拉到最下方。 要操作的頁面元素不在吸視范圍,無法進行操作,需要拖動滾動條
其實,實現這個功能只要一行代碼,但由於不懂js ,所以花了不小力氣找到這種方法。
用於標識滾動條位置的代碼
<body onload= "document.body.scrollTop=0 ">
<body onload= "document.body.scrollTop=100000 ">
如果滾動條在最上方的話,scrollTop=0 ,那么要想使用滾動條在最可下方,可以scrollTop=100000 ,這樣就可以使滾動條在最下方。
場景一
先來解決場第一個問題,法律條款是一個內嵌窗口,通過firebug工具可以定位到內嵌入窗口可以定位到元素的id ,可以通過下面的代碼實現。
js="var q=document.getElementById('id').scrollTop=10000" driver.execute_script(js)
注:由於法律條款的文字必須被閱讀並接受才能進行下一步, 所以必須先將滾動條滑到底部,然后“接受”按鈕才可用, 點擊接受以后“下一步”按鈕才可用。
場景二
有滾動條的頁面到處可見,這個就比較容易找例子,我們以操作百度搜索結果頁為例:
#coding=utf-8 from selenium import webdriver import time #訪問百度 driver=webdriver.Firefox() driver.get("http://www.baidu.com") #搜索 driver.find_element_by_id("kw").send_keys("selenium") driver.find_element_by_id("su").click() time.sleep(3) #將頁面滾動條拖到底部 js="var q=document.documentElement.scrollTop=10000" driver.execute_script(js) time.sleep(3) #將滾動條移動到頁面的頂部 js="var q=document.documentElement.scrollTop=0" driver.execute_script(js) time.sleep(3) driver.quit()
轉自: http://tech.ddvip.com/2013-10/1383059700204981.html
以下是我自己的代碼, C# + IE:
using Se = OpenQA.Selenium; using SIE = OpenQA.Selenium.IE; // SIE.InternetExplorerOptions _IEOptions = null; SIE.InternetExplorerDriver _IEDriver = null; // init Internet driver private void InitIE() { _IEOptions = new SIE.InternetExplorerOptions(); _IEOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true; _IEOptions.UnexpectedAlertBehavior = SIE.InternetExplorerUnexpectedAlertBehavior.Default; _IEOptions.ElementScrollBehavior = SIE.InternetExplorerElementScrollBehavior.Bottom; _IEDriver = new SIE.InternetExplorerDriver(_IEOptions); } private void Scroll Bar() { IList<Se.IWebElement> frames = _IEDriver.FindElements(Se.By.TagName("frame")); Se.IWebElement frameDisplay = null; Se.IWebElement frameControlPanel = null; foreach (var frame in frames) { if (frame.GetAttribute("name") == "ElementDisplayFrame") { frameDisplay = frame; } else if (frame.GetAttribute("name") == "ControlPanelFrame") { frameControlPanel = frame; } } if (frameDisplay != null) { _IEDriver.SwitchTo().Frame(frameDisplay); // scroll to bottom Se.IWebElement ndaContainer = _IEDriver.FindElement(Se.By.Id("ndacontainer")); string id = ndaContainer.GetAttribute("id"); var js = "var q = document.getElementById('" + id + "').scrollTop=10000"; _IEDriver.ExecuteScript(js, null); ElementHP.Wait(_IEDriver); Se.IWebElement yesButton = _IEDriver.FindElement(Se.By.XPath("//input[@name='I1']")); if (yesButton != null && yesButton.Enabled) { yesButton.Click(); } } }