JavaScript爬虫开发中,异常处理至关重要。 网络请求和HTML解析过程容易出错,有效的异常处理能确保爬虫程序的稳定运行。 try...catch
语句是JavaScript中处理异常的主要方法。
以下示例演示如何使用try...catch
结合axios
(HTTP请求)和cheerio
(HTML解析)库来构建一个健壮的JavaScript爬虫:
const axios = require('axios');
const cheerio = require('cheerio');
async function fetchData(url) {
try {
const response = await axios.get(url);
const html = response.data;
const $ = cheerio.load(html);
// 处理解析后的数据,例如:
const title = $('title').text();
const paragraphs = $('p').map((i, el) => $(el).text()).get();
return { title, paragraphs };
} catch (error) {
console.error(`Error fetching or parsing ${url}:`, error);
// 可选:返回一个默认值或抛出错误,取决于你的需求
return null; // 或 throw error;
}
}
// 使用示例
fetchData('https://www.example.com')
.then(data => {
if (data) {
console.log('