1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| const puppeteer = require('puppeteer'); const https = require('https'); const fs = require('fs'); const { v4 } = require('uuid');
const isElementVisible = async (page, selector) => { let visible = true; await page .waitForSelector(selector, { visible: true, timeout: 2000 }) .catch(() => { visible = false; }); return visible; };
(async () => { const chromePath = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe" const browser = await puppeteer.launch({ executablePath: chromePath, headless: false }); const page = await browser.newPage(); await page.goto('https://pvp.qq.com/hdy/p1/all_works.html');
selectorForLoadMoreButton = "a.btn-load.js-load-more" let loadMoreVisible = await isElementVisible(page, selectorForLoadMoreButton); while (loadMoreVisible) { await page .click(selectorForLoadMoreButton) .catch(err => console.log("click load more button err: ", err)); loadMoreVisible = await isElementVisible(page, selectorForLoadMoreButton); }
const ulHandle = await page.$('ul#rankingList') const imageUrls = await ulHandle.$$eval("li>img.image", nodes => nodes.map(node => node["src"]))
await browser.close()
console.log("total images count: ", imageUrls.length)
for (imageUrl of imageUrls) { try { const imageData = await getImageData(imageUrl) await writeToFile('./yunzhongjun', imageData) } catch (error) { console.log(error) } } })();
function getImageData (imageUrl) { console.log(imageUrl) return new Promise((resolve, reject) => https.get(imageUrl, res => { let imgData = '' res.setEncoding('binary')
res.on('data', (chunk) => { imgData += chunk })
res.on('end', () => { resolve(imgData) })
res.on('error', err => { reject(err) }) }) ) }
function writeToFile (fileDir, imageData) { return new Promise((resolve, reject) => { let imageName = `${v4()}.jpg` let filePath = fileDir + '/' + imageName fs.writeFile(filePath, imageData, 'binary', err => { if (err) reject(err) resolve() }) }) }
|