// 使用 Node.js 和 cheerio 库进行简单的网页抓取
const axios = require('axios');
const cheerio = require('cheerio');
// 定义要抓取的 URL
const url = 'https://example.com';
// 发送 HTTP 请求获取页面内容
async function fetchPageContent() {
try {
const response = await axios.get(url);
const html = response.data;
// 使用 cheerio 加载 HTML 内容
const $ = cheerio.load(html);
// 抓取特定元素的内容,例如所有 <h1> 标签
const headings = [];
$('h1').each((index, element) => {
headings.push($(element).text());
});
console.log(headings);
} catch (error) {
console.error(`Error fetching the page: ${error.message}`);
}
}
fetchPageContent();
axios 发送 HTTP 请求,使用 cheerio 解析和操作 HTML。axios.get 方法获取网页的 HTML 内容。cheerio.load 将 HTML 内容加载到 $ 对象中,类似于 jQuery 的用法。<h1> 标签),并提取文本内容。上一篇:javascript 正则
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站