Created
November 7, 2015 00:29
-
-
Save LinZap/6b8335cb14da6db0cbb9 to your computer and use it in GitHub Desktop.
selenium-webdriver quick start
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var webdriver = require('selenium-webdriver'), | |
By = require('selenium-webdriver').By, | |
until = require('selenium-webdriver').until; | |
// open chrome | |
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build(); | |
// outset | |
driver.get('https://www.facebook.com/'); | |
driver.wait(driver.getTitle(),randTime()) | |
// login FB | |
.then(function(tit){ | |
var ele = { | |
email: driver.findElement(By.id('email')), | |
pass: driver.findElement(By.id('pass')), | |
btnlogin: driver.findElement(By.id('u_0_v')) | |
}; | |
ele.email.sendKeys('帳號'); | |
ele.pass.sendKeys('密碼'); | |
ele.btnlogin.click(); | |
return driver.wait(driver.getTitle(),randTime()); | |
}) | |
// go page | |
.then(function(tit){ | |
var keywords = "馬習會"; | |
driver.get('https://www.facebook.com/hashtag/'+keywords); | |
return driver.wait(driver.getTitle(),randTime()); | |
}) | |
// featch all of HashTags after got web title | |
.then(function(tit){ | |
// get all of elements by css selector | |
// return array | |
return driver.findElements(By.css('a[href*=hashtag]')).then(function(el) { return el; }); | |
}) | |
// elements.forEach | |
// wait for all of promises were resolved | |
.then(function(arr){ | |
var proms = []; | |
arr.forEach(function(el){ | |
// add all of promise | |
proms.push( | |
el.getText().then(function(txt){ | |
console.log(txt); | |
return txt; | |
}) | |
); | |
}); | |
return Promise.all(proms); | |
}) | |
// next step | |
.then(function(what){ | |
// do something here | |
}) | |
/* | |
wait rand time | |
*/ | |
function randTime() { | |
var min = arguments[0] || 500, | |
max = arguments[1] || 3000; | |
return Math.random() * (max - min) + min; | |
} |
Very helpful example! But why are you waiting a random amount of time?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Selenium Quickstart
說明
上面這個簡易的 sample 示範了以下一連串的行為
FYI
小結
在控制 browser 的過程中 selenium 全程使用 Promise。因此需要對於 Promise 有一點基礎的了解。由於官方沒有提供更多的 sample code,上面的寫法純屬個人風格,僅供參考。