## 簡介 在進行網頁爬蟲時,我們可以使用 Node.js 搭配 Selenium WebDriver 來模擬瀏覽器行為,從而獲取網頁上的資料。本篇筆記將介紹如何在 Node.js 環境下安裝 Selenium WebDriver,並使用它來實現簡單的網頁爬蟲功能。 關於 Selenium 的介紹請看這篇:[Selenium 簡介](https://hackmd.io/@BirdBird/B1Cwd3mgA) ## 安裝 首先,確保你的系統已經安裝了 Node.js。接著,使用 npm(Node.js 的套件管理器)來安裝所需的套件: ```bash npm install selenium-webdriver ``` ## 簡易範例 ```js const { Builder, By } = require('selenium-webdriver'); // 使用 Chrome 瀏覽器進行爬蟲 const driver = new Builder().forBrowser('chrome').build(); (async function example() { try { // 打開網頁 await driver.get('https://www.example.com'); // 獲取網頁標題 let title = await driver.getTitle(); console.log("Page title is: " + title); } finally { // 關閉瀏覽器 await driver.quit(); } })(); ``` ## 注意事項 在進行網頁爬蟲時,請務必遵守網站的使用條款和隱私政策,避免對網站造成不必要的負擔或侵犯用戶隱私。 ## 結語 使用 Node.js 搭配 Selenium WebDriver 可以輕鬆地實現網頁爬蟲功能,讓我們可以方便地獲取網頁上的資料。這個組合不僅功能強大,而且易於使用,適用於各種網頁爬蟲場景。