使用axios和cheerio可以实现多页抓取的步骤如下:
npm install axios cheerio
const axios = require('axios');
const cheerio = require('cheerio');
async function getPage(url) {
try {
const response = await axios.get(url);
return response.data;
} catch (error) {
console.error(`Failed to fetch page: ${url}`, error);
return null;
}
}
function parsePage(html) {
const $ = cheerio.load(html);
// 根据HTML结构和数据定位元素,并提取数据
const title = $('h1').text();
const content = $('#content').text();
return { title, content };
}
async function scrapePages() {
const urls = ['https://example.com/page1', 'https://example.com/page2', 'https://example.com/page3'];
for (const url of urls) {
const html = await getPage(url);
if (html) {
const data = parsePage(html);
console.log(data);
}
}
}
scrapePages();
以上步骤中,getPage函数使用axios发送GET请求获取页面的HTML内容,parsePage函数使用cheerio解析HTML内容并提取所需数据。主函数scrapePages定义了要抓取的页面URL列表,并通过循环依次抓取每个页面的数据。
注意:在实际使用中,可能需要进行异常处理、分页处理、数据存储等额外的逻辑。
一体化监控解决方案
企业创新在线学堂
云+社区沙龙online [技术应变力]
腾讯云数据湖专题直播
GAME-TECH
GAME-TECH
云+社区技术沙龙[第14期]
云+社区技术沙龙[第28期]
GAME-TECH
领取专属 10元无门槛券
手把手带您无忧上云