Skip to content

Instantly share code, notes, and snippets.

@LinZap
Created November 7, 2015 00:29
Show Gist options
  • Save LinZap/6b8335cb14da6db0cbb9 to your computer and use it in GitHub Desktop.
Save LinZap/6b8335cb14da6db0cbb9 to your computer and use it in GitHub Desktop.
selenium-webdriver quick start
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;
}
@LinZap
Copy link
Author

LinZap commented Nov 7, 2015

Selenium Quickstart

說明

上面這個簡易的 sample 示範了以下一連串的行為

  • 開啟 chrome
  • 連結到 facebook
  • 輸入帳號密碼並登入
  • 連結到新的畫面 https://www.facebook.com/hashtag/關鍵字
  • 使用類似 jQuery 的 selector 取出畫面上的元素
  • 印出每個元素中的字 (getText())
  • 全部元素印完才做下一個步驟

FYI

小結

在控制 browser 的過程中 selenium 全程使用 Promise。因此需要對於 Promise 有一點基礎的了解。由於官方沒有提供更多的 sample code,上面的寫法純屬個人風格,僅供參考。

@mLuby
Copy link

mLuby commented Apr 21, 2016

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