# JavaScript puppeteer ## 安裝方式 ### Step 1 需要先安裝[**node.js**](https://nodejs.org/dist/v16.17.0/node-v16.17.0-x64.msi) ### Step 2 在終端機上輸入以下代碼 :::info npm init -y ::: 然後 :::info npm install puppeteer ::: ### Step 3 建立一個**index.js** ## 開始學習 ### 拉入puppeteer 這邊是或不可缺的程式碼,用來連結指定網頁,中間可插入其他程式碼 ```javascript const puppeteer = require('puppeteer') const fs = require('fs/promises') async function start(){ const browser = await puppeteer.launch() const page = await browser.newPage() await page.goto("網址") await browser.close() } start() ``` ### 截圖 #### 視窗截圖 ```javascript await page.screenshot({path: "檔名.png"}) ``` #### 頁面截圖 ```javascript await page.screenshot({path: "檔名.png", fullPage: true}) ``` ### 抓取文字 #### 認識fs a代表是存放文件名稱 b代表是內容資料 ```javascript await fs.writeFile("a",b) ``` #### 文字轉成文件 兩個$符號代表有多項資料要處理,如果只有一項使用一個即可 ```javascript const names = await page.$$eval("文字代碼", (txts) => { return txts.map(x => x.textContent) }) await fs.writeFile("檔名.txt", names.join("\r\n")) ``` ### 抓取圖片 #### 圖片轉成圖檔 ```javascript const photos = await page.$$eval("img", (imgs) => { return imgs.map(x => x.src) }) for (const photo of photos){ const imagepage = await page.goto(photo) await fs.writeFile(photo.split("/").pop(), await imagepage.buffer()) } ``` ####
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up