JavaScript爬虫开发中,异常处理至关重要。 网络请求和HTML解析过程容易出错,有效的异常处理能确保爬虫程序的稳定运行。 try...catch语句是JavaScript中处理异常的主要方法。
以下示例演示如何使用try...catch结合axios (HTTP请求)和cheerio (HTML解析)库来构建一个健壮的JavaScript爬虫:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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(
以上就是js爬虫怎样进行异常处理的详细内容,更多请关注php中文网其它相关文章!