⭐️基础链接导航⭐️
服务器 → ☁️ 阿里云活动地址
看样例 → 🐟 摸鱼小网站地址
学代码 → 💻 源码库地址
一、前言
在本系列文章的早期章节中,我们已经成功地购买了服务器并配置了MySQL、Redis等核心中间件。紧接着,我们不仅建立了后端服务,还开发了我们的首个爬虫程序。后面我们还把爬取到的数据进行了保存,生成了一整套MVC的后端代码,并且提供了一个接口出来。
这篇文章呢我要开始前端开发部分了。与后端开发相比,前端开发的优势在于其直观性和即时反馈。开发者可以迅速看到自己代码的成果,这种“所见即所得”的体验极大地提升了开发的乐趣和满足感。在接下来的篇章中,我将展示如何将爬取到的热搜数据整合到前端界面中,使之以一种用户友好的方式呈现,大家姑妄看之。
二、前端应用搭建
我的前端技术栈还停留在四年前,那时候我主要使用的是Vue2和ElementUI。并不是说我认为Vue3或React不好,只是我更习惯使用我熟悉的技术。即便如此,这些技术依然能够带来不错的效果。如果你想要尝试不同的技术或组件库,那也是完全可以的。
1. 前端环境搭建
(1)安装node.js,下载相应版本的node.js,下载地址: https://nodejs.org/en/download/ ,下载完双击安装,点击下一步直到安装完成,建议下载版本的是:
v16.20.2
(2)安装完成后,附件里选择命令提示符(或者在开始的搜索框里输入cmd回车调出命令面板)输入:node -v回车,出现相应版本证明安装成功, node环境已经安装完成。
由于有些npm有些资源被屏蔽或者是国外资源的原因,经常会导致用npm安装依赖包的时候失败,所有我还需要npm的 国内镜像—cnpm。在命令行中输入:npm install -g cnpm --registry=https://registry.npmmirror.com
回车,大约需要3分钟,如果一直没有反应使用管理员身份运行cmd重试。
(3)安装全局vue-cli脚手架,用于帮助搭建所需的模板框架。输入命令:
cnpm install -g @vue/cli
回车等待完成。
(4)创建项目,首先我们要选定目录,然后再命令行中把目录转到选定的目录,假如我们打算把项目新建在e盘下的vue文件夹中则输入下面的命令: e:回车,然后cd vue,然后输入命令:
vue create summo-sbmy-front-web
,回车,然后它就会让你选择vue2还是vue3,选择vue2后点击enter,它就会创建好项目并且下载好依赖。
(5)启动项目,首先切换到summo-sbmy-front-web目录,然后执行
npm run serve
,项目运行成功后,浏览器会自动打开localhost:8080(如果浏览器没有自动打开 ,可以手动输入)。运行成功后,会看到Welcome to Your Vue.js App页面。
2. 脚手架处理
我的开发工具是VS Code,免费的,下载地址如下: https://code.visualstudio.com/。
(1)文件和代码清理
删除components下的HelloWorld.vue文件
删除assets下的logo.png文件
原始App.vue代码如下
删除不必要的代码,不然启动会报错
(2)axios和element-ui依赖引入
执行安装命令
下载完上面这两个组件后,去main.js中注册组件,然后才能使用,main.js代码如下:
(3)封装apiService.js方便调用接口
在src目录下创建一个文件夹名为config,创建一个apiService.js,代码如下:
三、前端热搜组件
1. 组件介绍
首先,成品的热搜组件样式如下,包括标题(图标+名称)、内容区(排序、标题、热度),点击标题可以跳转到指定的热搜文章。
2. 组件实现
在components目录下创建HotSearchBoard.vue
文件,代码如下:
在App.vue中添加热搜组件,由于不止一个热搜,我把它做成了一个数组
最终的项目结构和文件如下
代码不难,无非就是使用卡片和列表对热搜进行展示,还有就是我加了一些样式,比如前三名的排序有颜色,字体改了改。
四、小结一下
在本篇文章中,我主要展示前端代码逻辑。至于后端,也做了一些更新,比如新增了queryType接口和跨域请求的处理,但这些内容都是基础的,你下载代码后就能一目了然,不懂的评论区交流,或者+我:hb1766435296
。之前的准备工作终于开始见到成效,虽然看起来简单,但实际上解决了不少复杂问题。现在,服务器、前端和后端的基础都打好了,接下来我会继续开发,增加更多功能。
关于爬虫部分,我已经成功实现了针对12个不同网站的爬取功能。考虑到爬虫的逻辑相对简单,无需单独撰写文章来详细说明。因此,我计划在每篇文章的附录或额外部分简要介绍各个热搜网站的爬虫逻辑。这样的安排既能保证信息的完整性,又不会让文章显得过于冗长。
番外:知乎热搜爬虫
1. 爬虫方案评估
知乎热搜是这样的, 接口是: https://www.zhihu.com/api/v3/feed/topstory/hot-lists/total
数据还算完备,有标题、热度、封面、排序等,知乎的热搜接口返回的数据格式是JSON,这种比返回HTML更简单。
2. 网页解析代码
这个就可以使用Postman生成调用代码,流程我就不赘述了,直接上代码,ZhihuHotSearchJob:
知乎的热搜数据是自带唯一ID的,不需要我们手动生成,非常方便。