透過NodeJS爬蟲套件開啟瀏覽器並自動登入FB帳號密碼
行程準備
chromedriver //依照自己的Chrome瀏覽器版本下載chromedriver
安裝selenium-webdriver套件
npm i selenium-webdriver
引入selenium-webdriver相關套件
const webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until;
const chrome = require('selenium-webdriver/chrome');
開啟瀏覽器並填入網址
driver=await new webdriver.Builder().forBrowser("chrome").withCapabilities(options).build();
await driver.get('https://www.facebook.com/login');
透過Xpath取出網頁元件
const fb_email_ele = await driver.wait(until.elementLocated(By.xpath(`//*[@id="email"]`)));
fb_email_ele.sendKeys(fb_username);//帳號輸入框
const fb_pass_ele = await driver.wait(until.elementLocated(By.xpath(`//*[@id="pass"]`)));
fb_pass_ele.sendKeys(fb_userpass);//密碼輸入框
const login_ele = await driver.wait(until.elementLocated(By.xpath(`//*[@id="loginbutton"]`)));
login_ele.click();//登入按鈕
完整程式碼
const webdriver = require('selenium-webdriver'), By = webdriver.By, until = webdriver.until;
const chrome = require('selenium-webdriver/chrome');
const options = new chrome.Options();
const fb_username = '你的帳號';
const fb_userpass ='你的密碼';
async function loginFacebook() {
let driver;
try {
driver=await new webdriver.Builder().forBrowser("chrome").withCapabilities(options).build();
} catch (e) {
console.log('無法建立瀏覽器', e);
return;
}
const web = 'https://www.facebook.com/login';
await driver.get(web);
const fb_email_ele = await driver.wait(until.elementLocated(By.xpath(`//*[@id="email"]`)));
fb_email_ele.sendKeys(fb_username);
const fb_pass_ele = await driver.wait(until.elementLocated(By.xpath(`//*[@id="pass"]`)));
fb_pass_ele.sendKeys(fb_userpass);
const login_ele = await driver.wait(until.elementLocated(By.xpath(`//*[@id="loginbutton"]`)));
login_ele.click();
}
loginFacebook();