我需要抓取 113 个 URL 的列表,以从这些 URL 中收集 Title、ImageURL 和 Content 并将它们放入稍后导入的 JSON/文本文件。
但我似乎无法让它正常工作。我现在已经让循环开始工作,就像转到 URL 一样,但返回结果未定义,不确定为什么返回的数据没有通过。
我可以得到一些帮助吗?
编辑
const puppeteer = require('puppeteer');
let scrape = async (i, url) => {
const browser = await puppeteer.launch({
headless: false // Show Browser
});
// Load a new page
const page = await browser.newPage();
// Set viewport size
await page.setViewport({ width: 1366, height: 768, deviceScaleFactor: 1 });
// Go to URL
await page.goto(`${url}`, { waitUntil: 'networkidle2' });
// Run the scrape over the page
const results = await page.evaluate(() => {
// H2 Heading
let title = document.querySelector('div.wsite-section-elements > h2.wsite-content-title').innerText;
// Image
let imageURL = document.querySelector('div.wsite-section-elements > div > div > a> img').getAttribute('src');
// Paragraph
let txtContent = document.querySelector('div.wsite-section-elements > div.paragraph').innerText;
});
//Close Browser
await browser.close();
// Return scrape results
return results;
};
(async () => {
// Pages to scrape
let pageURLs = ['https://www.bibleed.com/the-divine-origin-of-the-bible.html','https://www.bibleed.com/the-bible-our-guide.html'];
for(let i = 0; i < pageURLs.length; i++)
{
await scrape(i, pageURLs[i]).then((value) => {
console.log(i, ': ', value);
});
}
// Write to file
//const fs = require('fs');
//fs.writeFileSync('webScrape3.txt', JSON.stringify(result), err => err ? console.log(err): null);
})();
最佳答案
您在 for 循环内创建一个 pamphletData
变量,该变量在循环外部不可访问。因此,当您执行 JSON.stringify(pamphletData)
时,您实际上执行的是 JSON.stringify(undefined)
。
关于javascript - puppeteer 网络抓取问题 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60448730/