当然可以。axioscheerio 是两个非常流行的 JavaScript 库,分别用于 HTTP 请求和 HTML 解析。它们在编写网络爬虫时非常有用。下面是对这两个库的详细介绍及其使用流程。

Axios

axios 是一个基于 Promise 的 HTTP 客户端,可以用于浏览器和 Node. Js 环境。它简化了发送 HTTP 请求的过程,并且支持多种请求方法、拦截器、中断请求等功能。

功能

  • 发送 HTTP 请求(GET、POST、PUT、DELETE 等)
  • 支持请求和响应拦截器
  • 支持取消请求
  • 自动转换 JSON 数据
  • 支持跨域请求

安装

如果你还没有安装 axios,可以使用以下命令进行安装:

bun add axios

使用流程

  1. 发送 GET 请求

    import axios from 'axios';
     
    async function fetchHTML(url: string): Promise<string> {
      const response = await axios.get(url);
      return response.data;
    }
     
    fetchHTML('https://example.com').then(html => {
      console.log(html);
    });
  2. 发送 POST 请求

    import axios from 'axios';
     
    async function postData(url: string, data: object): Promise<void> {
      const response = await axios.post(url, data);
      console.log(response.data);
    }
     
    postData('https://example.com/api', { key: 'value' });
  3. 使用拦截器

    import axios from 'axios';
     
    axios.interceptors.request.use(request => {
      console.log('Starting Request', request);
      return request;
    });
     
    axios.interceptors.response.use(response => {
      console.log('Response:', response);
      return response;
    });
     
    axios.get('https://example.com');

Cheerio

cheerio 是一个快速、灵活且精巧的 jQuery 核心实现,适用于服务器端。它提供了一套类似于 jQuery 的 API,用于在 Node. Js 中解析和操作 HTML 文档。

功能

  • 解析 HTML 和 XML 文档
  • 提供类似于 jQuery 的 DOM 操作 API
  • 支持 CSS 选择器
  • 处理表单、表格、链接等常见 HTML 元素

安装

如果你还没有安装 cheerio,可以使用以下命令进行安装:

bun add cheerio

使用流程

  1. 加载 HTML

    import cheerio from 'cheerio';
     
    const html = '<html><body><h1>Hello, world!</h1></body></html>';
    const $ = cheerio.load(html);
     
    console.log($('h1').text()); // 输出:Hello, world!
  2. 从 URL 中提取链接

    import axios from 'axios';
    import cheerio from 'cheerio';
     
    async function fetchLinks(url: string): Promise<string[]> {
      const { data } = await axios.get(url);
      const $ = cheerio.load(data);
      const links: string[] = [];
     
      $('a').each((index, element) => {
        const link = $(element).attr('href');
        if (link) {
          links.push(link);
        }
      });
     
      return links;
    }
     
    fetchLinks('https://example.com').then(links => {
      console.log(links);
    });
  3. 提取特定元素的文本

    import axios from 'axios';
    import cheerio from 'cheerio';
     
    async function fetchHeadings(url: string): Promise<string[]> {
      const { data } = await axios.get(url);
      const $ = cheerio.load(data);
      const headings: string[] = [];
     
      $('h1, h2, h3').each((index, element) => {
        headings.push($(element).text());
      });
     
      return headings;
    }
     
    fetchHeadings('https://example.com').then(headings => {
      console.log(headings);
    });

综合示例

结合 axioscheerio,可以编写一个简单的网络爬虫,抓取网页中的所有链接:

import axios from 'axios';
import cheerio from 'cheerio';
 
const url = 'https://example.com';
 
async function fetchHTML(url: string): Promise<string> {
  const { data } = await axios.get(url);
  return data;
}
 
async function parseHTML(html: string): Promise<string[]> {
  const $ = cheerio.load(html);
  const links: string[] = [];
 
  $('a').each((index, element) => {
    const link = $(element).attr('href');
    if (link && link.startsWith('http')) {
      links.push(link);
    }
  });
 
  return links;
}
 
async function main() {
  try {
    const html = await fetchHTML(url);
    const links = await parseHTML(html);
    console.log('Found links:', links);
  } catch (error) {
    console.error('Error occurred:', error);
  }
}
 
main();

这个综合示例展示了如何使用 axios 发送 HTTP 请求,获取网页内容,并使用 cheerio 解析 HTML 文档,提取所有链接。