Cheerio是一个轻量级的服务器端HTML解析和操作库,类似于jQuery的API。在Node.js环境中,它常用于网页抓取和数据提取。
Cheerio实现了jQuery核心的一个子集,专注于HTML解析和DOM操作,但不包含浏览器环境中的视觉效果或事件处理。
const cheerio = require('cheerio');
const html = '<a href="https://example.com">Link</a>';
const $ = cheerio.load(html);
const href = $('a').attr('href');
console.log(href); // 输出: https://example.com
const html = `
<a href="https://example.com/1">Link 1</a>
<a href="https://example.com/2">Link 2</a>
`;
const $ = cheerio.load(html);
$('a').each((index, element) => {
console.log($(element).attr('href'));
});
// 输出:
// https://example.com/1
// https://example.com/2
const html = `
<a class="external" href="https://external.com">External</a>
<a class="internal" href="/about">About</a>
`;
const $ = cheerio.load(html);
const externalLink = $('a.external').attr('href');
console.log(externalLink); // 输出: https://external.com
const html = '<a href="/products">Products</a>';
const $ = cheerio.load(html);
const baseUrl = 'https://example.com';
const absoluteUrl = new URL($('a').attr('href'), baseUrl).href;
console.log(absoluteUrl); // 输出: https://example.com/products
可能原因:
解决方案:
// 检查元素是否存在
if ($('a').length > 0) {
const href = $('a').attr('href');
console.log(href || 'No href attribute found');
} else {
console.log('No anchor elements found');
}
Cheerio只能解析静态HTML,对于JavaScript动态生成的内容,需要使用Puppeteer等工具。
const cheerio = require('cheerio');
const axios = require('axios'); // 用于获取网页内容
async function extractLinks(url) {
try {
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const links = [];
$('a').each((index, element) => {
const href = $(element).attr('href');
if (href) {
links.push({
text: $(element).text().trim(),
href: href
});
}
});
return links;
} catch (error) {
console.error('Error:', error.message);
return [];
}
}
// 使用示例
extractLinks('https://example.com')
.then(links => console.log(links));
这个示例展示了如何从一个网页中提取所有链接及其文本内容。
没有搜到相关的文章