页面展示如下↓
本demo采用前后端分离服务器的方式完成,首先先从后端开始。
1、后端开发
1.1 如何爬取到京东的数据?
我们使用的是jsoup来解析浏览器的数据,在爬取数据之前,我们要先明白,我们需要的数据是什么,因此让我们来看看京东的商品搜索页面。
初步看,如果要完成爬取数据到我们的页面上,至少需要获取到商品的标题,图片以及价格,因此F12查看一下网页源码。
易知,在J_goodsList标签下,一个个li标签中就有我们想要获取的数据,因此我们可以开始编写后端代码。
1.2 相关依赖的导入
在pom文件引入jsoup和springboot、elasticSearch的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>pers.fjl</groupId>
<artifactId>es-jd</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>es-jd</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<!-- 自定义es版本依赖否则会出bug-->
<elasticsearch.version>7.6.1</elasticsearch.version>
</properties>
<dependencies>
<!-- 解析网页-->
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.10.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
1.3 Jsoup工具类的编写
把获取的数据字段封装到Content实体类,加入到list中后返回。
package pers.fjl.utils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import pers.fjl.po.Content;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class HtmlParseUtil {
public static void main(String[] args) throws IOException{
new HtmlParseUtil().parseJD("java").forEach(System.out::println);
}
public List<Content> parseJD(String keyword) throws IOException {
// 获取请求 https://search.jd.com/Search?keyword=java
String url = "https://search.jd.com/Search?keyword=" + keyword + "&enc=utf-8";
// 解析网页,返回浏览器document页面对象
Document document = Jsoup.parse(new URL(url), 30000);
// 所有js能用的方法在这都可使用
Element element = document.getElementById("J_goodsList"); // 获取div标签J_goodsList
System.out.println(element.html());
// 数据都在li标签中
Elements lis = element.getElementsByTag("li");
ArrayList<Content> goodsList = new ArrayList<>();
for (Element el : lis) {
// 网页采用了懒加载,所以在src中无法直接获取
String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
String price = el.getElementsByClass("p-price").eq(0).text();
String title = el.getElementsByClass("p-name").eq(0).text();
Content content = new Content();
content.setImg(img);
content.setPrice(price);
content.setTitle(title);
goodsList.add(content);
}
return goodsList;
}
}
1.4 将返回的list加入到elasticSearch中
返回的list可以选择放入到数据库或者elasticSearch中,这里展示后者。
@Service
public class ContentService {
@Resource
private RestHighLevelClient restHighLevelClient;
// 1、解析数据放入es索引中
public Boolean parseContent(String keyword) throws Exception {
List<Content> contents = new HtmlParseUtil().parseJD(keyword);
// 把查询的数据放入到es中
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("2m"); // 超市时间2min
for (int i = 0; i < contents.size(); i++) {
// 批量添加
bulkRequest.add(new IndexRequest(ESconst.ES_INDEX) // 存到jd_goods索引中
.source(JSON.toJSONString(contents.get(i)), XContentType.JSON));
}
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
return !bulk.hasFailures();
}
}
controller层简单的两个方法,
package pers.fjl.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import pers.fjl.service.ContentService;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@CrossOrigin
@RestController
public class ContentController {
@Resource
private ContentService contentService;
@GetMapping("/parse/{keyword}")
public Boolean parse(@PathVariable("keyword") String keyword) throws Exception {
return contentService.parseContent(keyword);
}
@GetMapping("/search/{keyword}/{currentPage}/{pageSize}")
public List<Map<String, Object>> search(@PathVariable("keyword") String keyword,
@PathVariable("currentPage") int currentPage,
@PathVariable("pageSize") int pageSize) throws IOException {
return contentService.highLightSearchPage(keyword, currentPage, pageSize);
}
}
请求对应路径调用控制层方法
此处可看到,数据已经添加到es索引中。
1.5 将es中的数据返回到前端
其实只需要把需要的数据从mysql中或者es索引中拿出并封装到list返回即可。
package pers.fjl.service;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;
import pers.fjl.po.Content;
import pers.fjl.utils.ESconst;
import pers.fjl.utils.HtmlParseUtil;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@Service
public class ContentService {
@Resource
private RestHighLevelClient restHighLevelClient;
// 3、获取这些数据实现搜索高亮功能
public List<Map<String, Object>> highLightSearchPage(String keyword, int currentPage, int pageSize) throws IOException {
if (currentPage <= 1) {
currentPage = 1;
}
// 条件搜索
SearchRequest searchRequest = new SearchRequest("jd_goods");
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 分页
// 从第几条数据开始
sourceBuilder.from((currentPage - 1) * pageSize);
sourceBuilder.size(pageSize);
// 精准匹配
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
sourceBuilder.query(termQueryBuilder);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
// 高亮
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("title");
highlightBuilder.requireFieldMatch(false); // 只高亮显示第一个即可
highlightBuilder.preTags("<span style = 'color:red'>");
highlightBuilder.postTags("</span>");
sourceBuilder.highlighter(highlightBuilder);
// 执行搜素
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
// 解析结果
ArrayList<Map<String, Object>> list = new ArrayList<>();
for (SearchHit hit : searchResponse.getHits().getHits()) { //hits中的字段没有被高亮,因此要将es返回highlight中的高亮字段替换到hit中
// 解析高亮字段
Map<String, HighlightField> highlightFields = hit.getHighlightFields();
HighlightField title = highlightFields.get("title");
Map<String, Object> sourceAsMap = hit.getSourceAsMap(); // 原来的字段结果
if (title != null) { // 解析高亮字段,将原来字段替换为高亮字段
Text[] fragments = title.fragments();
String n_title = "";
for (Text text : fragments) {
n_title += text;
}
sourceAsMap.put("title", n_title); //高亮字段替换掉原来内容
}
sourceAsMap.put("id",hit.getId());
list.add(hit.getSourceAsMap());
}
return list;
}
}
2、前端开发
2.1 页面的编写
前端代码写的比较简洁,不难看懂,在此不做赘述。
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import axios from 'axios'
// 导入全局样式表
import './assets/css/global.css'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
Vue.config.productionTip = false
Vue.prototype.$http = axios
// 配置请求的跟路径
axios.defaults.baseURL = 'http://127.0.0.1:9090/'
new Vue({
router,
el: '#app',
render: h => h(App)
}).$mount('#app')
商品详情页的vue
<template>
<div>
<div id="mallPage" class=" mallist tmall- page-not-market ">
<!-- 头部搜索 -->
<div id="header" class=" header-list-app">
<div class="headerLayout">
<div class="headerCon ">
<!-- Logo-->
<h1 id="mallLogo">
<img src="../assets/images/jdlogo.png" alt="">
</h1>
<div class="header-extra">
<!--搜索-->
<div id="mallSearch" class="mall-search">
<form name="searchTop" class="mallSearch-form clearfix">
<fieldset>
<legend>天猫搜索</legend>
<div class="mallSearch-input clearfix">
<div class="s-combobox" id="s-combobox-685">
<div class="s-combobox-input-wrap">
<input v-model="pagination.keyword" type="text" autocomplete="off" value="dd" id="mq"
class="s-combobox-input" aria-haspopup="true">
</div>
</div>
<button type="submit" @click="searchItem" id="searchbtn">搜索</button>
</div>
</fieldset>
</form>
<ul class="relKeyTop">
<li><a>Java</a></li>
<li><a>前端</a></li>
<li><a>Linux</a></li>
<li><a>大数据</a></li>
<li><a>理财</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- 商品详情页面 -->
<div id="content">
<div class="main">
<!-- 品牌分类 -->
<form class="navAttrsForm">
<div class="attrs j_NavAttrs" style="display:block">
<div class="brandAttr j_nav_brand">
<div class="j_Brand attr">
<div class="attrKey">
品牌
</div>
<div class="attrValues">
<ul class="av-collapse row-2">
<li><a href="#"> vue </a></li>
<li><a href="#"> Java </a></li>
</ul>
</div>
</div>
</div>
</div>
</form>
<!-- 排序规则 -->
<div class="filter clearfix">
<a class="fSort fSort-cur">综合<i class="f-ico-arrow-d"></i></a>
<a class="fSort">人气<i class="f-ico-arrow-d"></i></a>
<a class="fSort">新品<i class="f-ico-arrow-d"></i></a>
<a class="fSort">销量<i class="f-ico-arrow-d"></i></a>
<a class="fSort">价格<i class="f-ico-triangle-mt"></i><i class="f-ico-triangle-mb"></i></a>
</div>
<!-- 商品详情 -->
<div class="view grid-nosku">
<div class="product" v-for="result in results" v-bind:key="result.id">
<div class="product-iWrap">
<!--商品封面-->
<div class="productImg-wrap">
<a class="productImg">
<img v-bind:src = "result.img">
</a>
</div>
<!--价格-->
<p class="productPrice">
<em><b>¥</b>{{result.price}}</em>
</p>
<!--标题-->
<p class="productTitle">
<a v-html="result.title"></a>
</p>
<!-- 店铺名 -->
<div class="productShop">
<span>店铺: Java </span>
</div>
<!-- 成交信息 -->
<p class="productStatus">
<span>月成交<em>999笔</em></span>
<span>评价 <a>3</a></span>
</p>
</div>
</div>
</div>
</div>
</div>
<div>
</div>
</div>
<!-- 卡片视图区域 -->
<el-card>
<!-- 搜索与添加区域 -->
<el-pagination align="center"
class="pagination"
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="pagination.currentPage"
:page-sizes="[2,5,10,15]"
:page-size="pagination.pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="100">
</el-pagination>
</el-card>
</div>
</template>
<script>
// import '../assets/js/jquery.min'
export default {
data () {
return {
test: 1,
pagination: { // 分页相关模型数据
currentPage: 1, // 当前页码
pageSize: 10, // 每页显示的记录数
total: 50, // 总记录数
keyword: null // 查询条件
},
results: [] // 搜索结果
}
},
methods: {
// 监听 switch 开关状态的改变
async searchItem () {
const keyword = this.pagination.keyword
const pageSize = this.pagination.pageSize
const currentPage = this.pagination.currentPage
const { data: res } = await this.$http.get(
`/search/${keyword}/${currentPage}/${pageSize}`
)
console.log(res)
this.results = res
},
// 切换页码
handleCurrentChange (currentPage) {
// 设置最新的页码
this.pagination.currentPage = currentPage
// 重新调用分页方法进行分页查询
this.searchItem()
},
handleSizeChange (newSize) {
this.pagination.pageSize = newSize
this.searchItem()
}
}
}
</script>
<style>
/*@import "../assets/css/style.css";*/
</style>