Cursor (https://www.cursor.so/)是 GPT-4 驱动的一款强大代码编辑器,可以辅助程序员进行日常的编码。

Cursor:GPT-4 驱动的强大代码编辑器

下面通过一个实际的例子来展示 Cursor 如何帮助你编程。

这个例子做的事情是网页抓取。抓取的目标是百度首页上的百度热搜,如下图所示。

Cursor:GPT-4 驱动的强大代码编辑器

我用的是 JavaScript 来实现的。

同时按下 Ctrl + K,给出的提示是:抓取 https://www.baidu.com/ 网站上的百度热搜。

Cursor 很快就给出了下面的一段代码。

// 使用 axios 和 cheerio 库抓取 https://www.baidu.com/ 网站上的百度热搜
const axios = require("axios");
const cheerio = require("cheerio");
async function fetchBaiduHotSearch() {
try {
const response = await axios.get("https://www.baidu.com/");
const $ = cheerio.load(response.data);
const hotSearchList = [];
$(".hotsearch-item").each((index, element) => {
const title = $(element).find(".title-content-title").text().trim();
hotSearchList.push(title);
});
console.log(hotSearchList);
} catch (error) {
console.error("Error fetching Baidu Hot Search:", error);
}
}
fetchBaiduHotSearch();

我的问题是:这段代码可以运行吗?

GPT-4 解释了这段代码的运行原理,还告诉我要用 npm 安装 axios和 cheerio 库。

运行了之后,发现输出结果为空数组。

把错误反馈给 GPT-4,它建议查看网页结构中的CSS选择器。

Cursor:GPT-4 驱动的强大代码编辑器

确认网页结构没有问题,反馈给 GPT-4。它进一步建议修改 HTTP 的 User-Agent 头来绕开百度的反爬虫处理。

Cursor:GPT-4 驱动的强大代码编辑器

按照 GPT-4 给出的代码进行修改。运行之后就得到了正确的结果。

Cursor:GPT-4 驱动的强大代码编辑器

最后让 GPT-4 格式化一下代码,就得到了最后可以使用的完整代码。

Cursor:GPT-4 驱动的强大代码编辑器

下面是最后产生的代码:

const axios = require("axios");
const cheerio = require("cheerio");
async function fetchBaiduHotSearch() {
try {
const response = await axios.get("https://www.baidu.com/", {
headers: {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3",
Referer: "https://www.baidu.com/",
},
});
const $ = cheerio.load(response.data);
const hotSearchList = [];
$(".hotsearch-item").each((index, element) => {
const title = $(element).find(".title-content-title").text().trim();
hotSearchList.push(title);
});
console.log(hotSearchList);
} catch (error) {
console.error("Error fetching Baidu Hot Search:", error);
}
}
fetchBaiduHotSearch();

Cursor 充分展现了 GPT-4 在辅助程序员编程方面的能力。最重要的是,Cursor 在国内可以直接访问和使用。赶紧下载使用吧。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。