node.js 自動化工具 (爬蟲) Selenium安裝使用

做過前端自動化,測試或者爬蟲的朋友應該對Selenium不陌生。


node.js 自動化工具 (爬蟲) Selenium安裝使用

Selenium

Selenium是一個用於支持和支持web瀏覽器自動化的一系列工具和庫。

它提供了模擬用戶與瀏覽器交互的擴展、用於縮放瀏覽器分配的分發服務器以及用於實現W3C WebDriver規範的基礎結構,該規範允許您為所有主要web瀏覽器編寫可互換的代碼。

這是一個開源的項目。Selenium的核心是WebDriver,它是一個編寫指令集的接口,可以在許多瀏覽器中互換運行。

簡而言之,Selenium可以被多種語言調用來模擬瀏覽器進行web訪問。通過使用Selenium,可以輕鬆的進行Web前端的自動化測試,也可以作為爬蟲。

目前Selenium支持Java, Python, C#, Ruby,JavaScript和Kotlin。

在node.js環境下安裝Selenium

  1. 安裝selenium webdriver,這是selenium的運行環境。
<code>D:\\Projects\\nodejs\\NodeDemo\\selenium>npm install selenium-webdriver --save
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

+ [email protected]
added 27 packages from 22 contributors and audited 32 packages in 10.196s

1 package is looking for funding
run `npm fund` for details

found 0 vulnerabilities/<code>
  1. 安裝Chrome驅動,也可以選擇安裝Firefox驅動或者其他瀏覽器驅動。Selenium支持多個瀏覽器。
<code>D:\\Projects\\nodejs\\NodeDemo\\selenium>npm install chromedriver --save
> [email protected] install D:\\Projects\\nodejs\\NodeDemo\\selenium\\node_modules\\chromedriver
> node install.js
Current existing ChromeDriver binary is unavailable, proceeding with download and extraction.
Downloading from file: https://chromedriver.storage.googleapis.com/80.0.3987.16/chromedriver_win32.zip
Saving to file: C:\\Users\\vincent\\AppData\\Local\\Temp\\80.0.3987.16\\chromedriver\\chromedriver_win32.zip
Received 1025K...
Received 2050K...
Received 3076K...
Received 4101K...
Received 4268K total.
Extracting zip contents
Copying to target path D:\\Projects\\nodejs\\NodeDemo\\selenium\\node_modules\\chromedriver\\lib\\chromedriver
Done. ChromeDriver binary available at D:\\Projects\\nodejs\\NodeDemo\\selenium\\node_modules\\chromedriver\\lib\\chromedriver\\chromedriver.exe
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

+ [email protected]
added 60 packages from 93 contributors and audited 137 packages in 110.907s

3 packages are looking for funding
run `npm fund` for details

found 1 low severity vulnerability
run `npm audit fix` to fix them, or `npm audit` for details/<code>

如果安裝Firefox驅動,將上述命令行中的 "chromedriver" 改成 "geckodriver" 即可。

  1. 設置路徑,將Chromedriver的路徑添加到系統環境變量path中。

Chromedriver的路徑在上一步安裝Chrome驅動時已經下載了,保存在 <your>\\node_modules\\chromedriver\\lib\\chromedriver目錄中,將該目錄加入到系統環境變量Path即可。否則在運行時,會報下列錯誤。/<your>

<code> D:\\Projects\\nodejs\\NodeDemo\\selenium>node app.js
(node:27800) UnhandledPromiseRejectionWarning:
Error: The ChromeDriver could not be found on the current PATH.
Please download the latest version of the ChromeDriver from http://chromedriver.storage.googleapis.com/index.html and ensure it can be found on your PATH./<code>


在node.js環境中使用Selenium

我這裡舉兩個例子。一是獲取某網站頻道,另一個是使用某網站進行搜索。

為了避免不必要的麻煩,我把該網站的網站隱藏了,如果朋友們感興趣,測試時可以在代碼中輸入相關網站的網址即可。

  • 獲取網站頻道

這裡的代碼使用了async/await,這樣就可以迴避嵌套回調函數了。關於async/await,感興趣的朋友可以看看這篇文章 。

<code>const {Builder, By, Key, until} = require('selenium-webdriver');

async function example() {
let driver = await new Builder().forBrowser('chrome').build();

// 訪問網址,可以將下面的字符串替換成自己想要訪問的網址即可。
await driver.get('https://xxxx.xxx.xxx')
//獲取網頁中的元素
let elements = await driver.findElements(By.className('channel-item'))
for(let e of elements) {
//獲取元素的文本
console.log(await e.getText());
}
}
//直接調用該async方法
example()/<code>

注意,上面相關的代碼都使用了await,方法頭加了async,在方法外面就可以直接調用了。

運行該代碼,程序會打開Chrome,訪問該網站,在控制檯打印出該網站的頻道。

  • 搜索網站內容

找到網站搜索文本框對應的css class,邏輯和上面一樣,不同的是再獲取到WebElement後,調用sendKeys方法即可進行搜索。

<code>const {Builder, By, Key, until} = require('selenium-webdriver');

async function example() {
let driver = await new Builder().forBrowser('chrome').build();
// 訪問網址,可以將下面的字符串替換成自己想要訪問的網址即可。
await driver.get('https://xxxx.xxxx.com')
await driver.findElement(By.className("tt-input__inner")).then(function(source) {

source.sendKeys('vincent', Key.ENTER)
})
}

example()/<code>

運行該js文件,程序會自動打開Chrome瀏覽器,再搜索文本框中輸入'vincent'並點擊回車進行搜索。

關於上面Selenium的介紹或者示例代碼,如果有問題,歡迎朋友們留言討論。


分享到:


相關文章: