Selenium-webdriver基本使用
准備
① node.js 的安裝和配置略
② Selenium-webdriver
npm install -save selenium-webdriver
③ 驅動
chromedriver 歡迎大家FQ下載:https://sites.google.com/a/chromium.org/chromedriver/downloads。然后找個環境路徑存一下就可以調用了。
IEdriver github下載:https://github.com/SeleniumHQ/selenium/wiki/InternetExplorerDriver 。 同樣環境路徑保存。
注意:IE玩家把internet選項-安全- 四個選項的啟動保護模式都關掉!
PhantomJS 直接解壓,把bin目錄放在環境路徑中
Opera以及geckodriver試了一下,對最新版opera和firefox支持並不好。可以下載較低的版本使用。
一、基本使用
const {Builder, By, Key, until, Button} = require("selenium-webdriver"); let broswer = new Builder().forBrowser('ie').build() #這里使用了ie引擎 broswer.get('http://www.baidu.com') broswer.quit() // 表示關閉瀏覽器 //drive.close()表示關閉當前窗口
二、選擇器
broswer.findElement(By.name('btnG')); broswer.findElement({id:"btnG"}); element.findElement(); //同樣可以對元素使用findElement方法 findElements //查找多個元素 By.className(classname) By.css(selector) #css-selector By.id(id) By.name(name) By.linkText(text) By.partialLink(text) By.xpath() By.js() //Locates an elements by evaluating a JavaScript expression. The result of this expression must be an element or list of elements.
三、屬性獲取
//獲取代碼: browser.getPageSource().then(function(souce) {console.log(souce); //獲取網頁標題: browser.getTitle().then(b=>{console.log(b)}); //獲取當前url: browser.getCurrentUrl().then(b=>{console.log(b)}); //element為web元素對象,為findelement()的返回對象
element.getText().then(b=>{console.log("text",b)}) //返回里面沒有被隱藏的文字(不帶標簽) element.getTagName().then(b=>{console.log("Tagname",b)}) //返回標簽名 element.getId().then(b=>{console.log("ID",b)}) //返回這個element服務器分配的不透明id elements.getCssValue().then(=>{console.log("CSSvalue",b)}) //返回該element的CSS屬性 //其他屬性: element.getAttribute("class").then(b=>{console.log(b)})
四、等待
//等待元素: browser.wait(until.elementLocated(By.id('foo')), 10000); browser.wait(function() { return driver.getTitle().then(function(title) { console.log(11111111); return title === 'webdriver - Google Search'; }); }, 1000); browser.wait(until.titleIs('webdriver - Google Search'), 1000) //settimeouts browser.manage().setTimeouts(args) // args參數 {implicit: (number|null|undefined), pageLoad: (number|null|undefined), script: (number|null|undefined)} implicit:等待元素加載的最大時間;pageLoad等待頁面加載完成的最大時間
五、操作
①input操作
//清空 element.clear(); //輸入 element.sendKeys("webdriver"); element.sendKeys(Key.ENTER); element.submit(); //以submit命令提交執行
②截圖
broswer.takeScreenshot().then() //返回頁面png截圖
element.takeScreenshoot().then() //返回元素png截圖
③鼠標操作
//單擊鼠標 element.click() //連鎖動作(action對象) const actions = driver.actions(); actions .keyDown(SHIFT) .move({origin: el}) .press() .release() .keyUp(SHIFT) .perform(); //actions對象以perform()作為動作鏈結尾,表示命令執行 //具體方法如下: actions.clear() //清空所有動作,按鍵和狀態 actions.click(element) //對element左鍵單擊一次 actions.contextClick(element) //對element右鍵單擊一次 actions.doubleClick(element) //對element雙擊一次 actions.dragAndDrop(ele_from,to) //單擊鼠標拖動ele_from元素,如果to是坐標{x:number,y:number}移動距離;如果to是元素移動到to元素中心,並釋放鼠標。 actions.keyDown(key) //按下鍵盤的key鍵 actions.keyUp(key) //釋放key鍵 actions.move(options) //移動參數如下: //options ({duration: (number|undefined), origin: (Origin|WebElement|undefined), x: (number|undefined), y: (number|undefined)}|undefined)
//origin是起始位置,默認為鼠標當前位置,可以設置元素為起始位置。x,y為偏移量。duration為持續時間默認(100ms) actions.press(button) //按下鼠標 button默認是鼠標左鍵,有LEFT,RIGHT,MIDDLE三個值,通過Button.LEFT....獲得 actions.release(button) //釋放鼠標,默認左鍵 actions.sendKeys() //同sendkeys actions.pause(ms,devices) //暫停ms時間,如果devices沒有指定,會創建一個針對所有的事件
舉例:

let actions = driver.actions({async: true}); actions.keyDown(Key.SHIFT); actions.pause(actions.mouse()) // Pause for shift down .press(Button.LEFT) .move({x: 10, y: 10}) .release(Button.LEFT); actions .pause( actions.keyboard(), // Pause for press left actions.keyboard(), // Pause for move actions.keyboard()) // Pause for release left .keyUp(Key.SHIFT); await actions.perform(); actions.mouse(); actions.keyboard() //分別代表鼠標和鍵盤設備
更多細節參考:http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/input_exports_Actions.html
六、options對象
通過let options = broswer.manage() 獲得
options.addCookie({name: 'foo', value: 'bar'}) options.deleteAllCookies() //刪除所有cookies options.deleteCookie(name) //按照name刪除 options.getCookie(name) //拿到name字段的cookie值,為promise對象 options.getCookies() //返回所有cookies,為promise對象
七、nav對象
通過let nav = broswer.navigate()獲得
nav有四個方法分別為:
nav.back();
nav.forward();
nav.refresh();
nav.to(url);
分別為后退,前進,刷新,跳轉到url
八、其他
①browser.excuteScript(script) //在當前frame中執行js代碼
②brower.switchTo() //targetlocator
targetlocator對象參見:http://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/webdriver_exports_TargetLocator.html
其中targetlocator.frame(id)可以用來切換frame。通過parentFrame()切回
更多API詳見:http://seleniumhq.github.io/selenium/docs/api/javascript/index.html
p.s. 根據瀏覽器版本和引擎不同,部分方法存在問題。
注意:一些執行操作的promise對象,需要合理利用async和await方法