使用Cursor写爬虫:从零开始构建你的数据抓取工具

1,420 阅读4分钟

今天要和大家分享一个非常实用的小项目——如何使用Node.js和Cursor编写一个简单的微博热搜爬虫。如果你是编程新手或者对网络爬虫感兴趣,那么这篇文章绝对适合你。我们将一步步地讲解如何通过发送HTTP请求、解析HTML内容以及将数据保存为CSV文件来实现这个小项目。

项目背景

Cursor集成了AI大模型来提供更智能的编码辅助功能。这样的工具可以显著提高开发效率和代码质量。随着社交媒体平台如微博等成为信息传播的重要渠道,实时获取热门话题变得越来越重要。本教程将教你如何利用Node.js及相关库来抓取微博热搜榜,并将这些数据存储到本地CSV文件中,方便后续分析或展示。

配置Cursor

  1. 下载Cursor

网站自取www.cursor.com/

2.添加AI

7a1514e68418360111e61d2fec7f9e0a_720.png 点击设置后再点击Models配置自己的AI大模型,如图我自己添加了一个通义千问大模型, 再往下拉配置API KET

80a4e444a83138695f0ce12a92c0eddc.png

配置完成后打开聊天框并且输入你要问的问题他会回答你的问题,如图是问的是如何生成爬虫的问题他会逐步告诉你怎么做并生成代码

63e51f059882ee15b67907930226e6d8.png

准备工作

首先确保你的电脑上已经安装了Node.js。接着,你需要安装几个必要的npm包,包括request-promise用于发送HTTP请求,cheerio用于解析HTML文档,以及csv-writer用来生成CSV格式的数据文件。你可以通过运行以下命令来安装它们:

npm install request-promise cheerio csv-writer

代码演示

main.js文件

  1. 引入依赖库

    const request = require('request-promise');
    const cheerio = require('cheerio');
    const createCsvWriter = require('csv-writer').createObjectCsvWriter;
    
    • request-promise:用于发送HTTP请求。
    • cheerio:用于解析HTML文档,类似于jQuery的选择器语法。
    • createCsvWriter:用于创建CSV文件写入器。
  2. 定义目标URL

    const url = 'https://tophub.today/n/KqndgxeLl9';
    
    • 定义要抓取的网页地址,这里是今日热榜的URL。
  3. 发送HTTP请求获取网页内容

    request(url)
        .then(html => {
            // 使用cheerio加载网页内容
            const $ = cheerio.load(html);
    
            // 定义一个数组来存储热榜信息
            const hotList = [];
    
            // 遍历表格中的每一行
            $('.jc table tr').each((index, element) => {
                // 跳过表头行
                if (index === 0) return;
    
                // 提取排名、标题、热度和链接
                const rank = $(element).find('td:nth-child(1)').text().trim();
                const title = $(element).find('td:nth-child(2) a').text().trim();
                const heat = $(element).find('td:nth-child(3)').text().trim();
                const link = 'https://tophub.today' + $(element).find('td:nth-child(2) a').attr('href');
    
                // 将提取的信息添加到数组中
                hotList.push({ rank, title, heat, link });
            });
    
            // 定义CSV写入器
            const csvWriter = createCsvWriter({
                path: 'weibo_hotlist.csv',
                header: [
                    { id: 'rank', title: '排名' },
                    { id: 'title', title: '标题' },
                    { id: 'heat', title: '热度' },
                    { id: 'link', title: '链接' }
                ]
            });
    
            // 将数据写入CSV文件
            csvWriter.writeRecords(hotList)
                .then(() => console.log('热榜信息已成功保存到 weibo_hotlist.csv 文件中'));
        })
        .catch(err => console.error(err));
    
    • 发送HTTP请求

      Javascript
      深色版本
      request(url)
          .then(html => {
              // 处理返回的HTML内容
          })
          .catch(err => console.error(err));
      
      • 使用request-promise发送GET请求到指定的URL,并在请求成功后处理返回的HTML内容。如果请求失败,则捕获错误并打印到控制台。
    • 使用cheerio加载网页内容

      const $ = cheerio.load(html);
      
      • 使用cheerio加载HTML内容,这样就可以使用类似jQuery的选择器来操作DOM元素。
    • 定义一个数组来存储热榜信息

      const hotList = [];
      
      • 创建一个空数组hotList,用于存储从页面中提取的每条热搜信息。
    • 遍历表格中的每一行

      $('.jc table tr').each((index, element) => {
          // 跳过表头行
          if (index === 0) return;
      
          // 提取排名、标题、热度和链接
          const rank = $(element).find('td:nth-child(1)').text().trim();
          const title = $(element).find('td:nth-child(2) a').text().trim();
          const heat = $(element).find('td:nth-child(3)').text().trim();
          const link = 'https://tophub.today' + $(element).find('td:nth-child(2) a').attr('href');
      
          // 将提取的信息添加到数组中
          hotList.push({ rank, title, heat, link });
      });
      
      • 使用$('.jc table tr')选择器找到所有表格行(tr)。
      • 使用.each()方法遍历每一行。
      • 如果当前行是表头行(即index === 0),则跳过。
      • 从每一行中提取排名、标题、热度和链接信息,并将其添加到hotList数组中。
    • 定义CSV写入器

      const csvWriter = createCsvWriter({
          path: 'weibo_hotlist.csv',
          header: [
              { id: 'rank', title: '排名' },
              { id: 'title', title: '标题' },
              { id: 'heat', title: '热度' },
              { id: 'link', title: '链接' }
          ]
      });
      
      • 创建一个CSV写入器,指定输出文件路径为weibo_hotlist.csv,并定义CSV文件的列头。
    • 将数据写入CSV文件

      csvWriter.writeRecords(hotList)
          .then(() => console.log('热榜信息已成功保存到 weibo_hotlist.csv 文件中'));
      
      • 使用writeRecords方法将hotList数组中的数据写入CSV文件。

      • 当数据成功写入文件时,打印一条消息到控制台。

      1. 完整代码以及效果展示
      const request = require('request-promise');
      const cheerio = require('cheerio');
      const createCsvWriter = require('csv-writer').createObjectCsvWriter;
      
      // 定义目标URL
      const url = 'https://tophub.today/n/KqndgxeLl9';
      
      // 发送HTTP请求获取网页内容
      request(url)
      .then(html => {
      // 使用cheerio加载网页内容
      const $ = cheerio.load(html);
      
      // 定义一个数组来存储热榜信息
      const hotList = [];
      
      // 遍历表格中的每一行
      $('.jc table tr').each((index, element) => {
          // 跳过表头行
          if (index === 0) return;
      
          // 提取排名、标题、热度和链接
          const rank = $(element).find('td:nth-child(1)').text().trim();
          const title = $(element).find('td:nth-child(2) a').text().trim();
          const heat = $(element).find('td:nth-child(3)').text().trim();
          const link = 'https://tophub.today' + $(element).find('td:nth-child(2)                         a').attr('href');
      
          // 将提取的信息添加到数组中
          hotList.push({ rank, title, heat, link });
      });
      
      // 定义CSV写入器
      const csvWriter = createCsvWriter({
          path: 'weibo_hotlist.csv',
          header: [
              { id: 'rank', title: '排名' },
              { id: 'title', title: '标题' },
              { id: 'heat', title: '热度' },
              { id: 'link', title: '链接' }
          ]
      });
      
      // 将数据写入CSV文件
      csvWriter.writeRecords(hotList)
          .then(() => console.log('热榜信息已成功保存到 weibo_hotlist.csv 文件中'));
      })
      .catch(err => console.error(err));
      

      运行代码后你的文件下会多出一个名为weibo_hotlist.csv的文件

      效果如下

image.png

结语

使用像Cursor这样集成AI大模型的代码编辑器,可以显著提高开发效率和代码质量。无论是智能代码补全、代码生成、代码审查还是其他功能,AI都能为开发者提供强大的支持。如果你对这类工具感兴趣,不妨尝试一下,看看它们如何改变你的编程体验。 以上就是整个过程的详细步骤啦!通过这个项目,你不仅学会了如何使用Node.js进行基本的网络爬虫开发,还掌握了如何操作DOM元素以及如何将数据输出为CSV格式。希望这篇教程对你有所帮助,也欢迎你在评论区分享你的学习体验或遇到的问题哦!