https://space.bilibili.com/95256449 原教程地址
创建一个实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Goods {
private String title;
private String img;
private String price;
private String shop;
}
写爬取数据的方法,此处以京东为例
@Component
public class HtmlParseUtils {
public ArrayList<Goods> getlist(String keyword) throws IOException {
//id----J_goodsList
//ul-----gl-warp clearfix
//url-----https://search.jd.com/Search?keyword=java
//attr----attr()是获取或设置某个元素的属性。
//eq(数字)-----获取当前标签的第(参数+1)个的内容,比如一个页面有多个a标签,getElementsByTag("a").eq(1)就是获取第2个a标签的内容
//查询的网站url
String url="https://search.jd.com/Search?keyword="+keyword;
//解析网站
Document document = Jsoup.parse(new URL(url), 30000);
//获得承载信息的div
Element element = document.getElementById("J_goodsList");
//获得列表也就是li
Elements lis = element.getElementsByTag("li");
//创建一个列表
ArrayList<Goods> list = new ArrayList<>();
for (Element li : lis) {
String img = li.getElementsByTag("img").eq(0).attr("source-data-lazy-img");
String title = li.getElementsByClass("p-name").eq(0).text();
String price = li.getElementsByClass("p-price").eq(0).text();
String shop = li.getElementsByClass("J_im_icon").eq(0).text();
Goods goods = new Goods();
goods.setTitle(title);
goods.setImg(img);
goods.setPrice(price);
goods.setShop(shop);
list.add(goods);
}
return list;
}
}
controller层
@Controller
public class Controllera {
@Autowired
private ContenService contenService;
@GetMapping("/index")
public String index() {
return "index";
}
//入库
@GetMapping("/parse/{keyword}")
@ResponseBody
public boolean addall(@PathVariable("keyword") String keyword) throws IOException {
boolean addall = contenService.addall(keyword);
return addall;
}
//查找
@GetMapping("/get/{keyword}/{page}/{num}")
@ResponseBody
public ArrayList<Map<String, Object>> get(@PathVariable("keyword") String keyword,
@PathVariable("page") Integer page,
@PathVariable("num") Integer num) throws IOException {
return contenService.getall(keyword,page,num);
}
//删除
@GetMapping("/delete")
@ResponseBody
public DeleteResponse delte() throws IOException {
DeleteResponse response = contenService.delete();
return response;
}
}
service层
@Service
public class ContenService {
@Autowired
private RestHighLevelClient restHighLevelClient;
@Autowired
private HtmlParseUtils htmlParseUtils;
//入库
public boolean addall(String keyword) throws IOException {
//先从爬取数据的方法获得信息并放到实体类
ArrayList<Goods> list = htmlParseUtils.getlist(keyword);
//创建批量操作的命令
BulkRequest bulkRequest = new BulkRequest();
//将数据批量放到索引
for (int i = 0; i < list.size(); i++) {
bulkRequest.add(new IndexRequest("jd_index").source(JSON.toJSONString(list.get(i)), XContentType.JSON));
}
//执行索引添加操作
BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
//bulk.hasFailures()如果为false则成功,所以是!bulk.hasFailures()
return !bulk.hasFailures();
}
public ArrayList<Map<String, Object>> getall(String keyword, Integer page, Integer num) throws IOException {
//创建jd_index的索引
SearchRequest request = new SearchRequest("jd_index");
//创建搜索命令
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//以title进行精确搜索
TermQueryBuilder termQueryBuilder = new TermQueryBuilder("title", keyword);
//执行精确搜索
sourceBuilder.query(termQueryBuilder);
if(page<1){
page=1;
}
//设置分页
sourceBuilder.from(page);
sourceBuilder.size(num);
//高亮设置
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.field("title");
highlightBuilder.preTags("<span style='color:blue'>");
highlightBuilder.postTags("</span>");
highlightBuilder.requireFieldMatch(false);//多个高亮显示
//执行高亮
sourceBuilder.highlighter(highlightBuilder);
//套娃执行搜索
request.source(sourceBuilder);
//套娃套娃执行索引命令
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
//list存的是map类型的数据
ArrayList<Map<String,Object>> list=new ArrayList<>();
//获得数据体
for (SearchHit fields : response.getHits().getHits()) {
//获得高亮的字段
Map<String, HighlightField> highlightFields = fields.getHighlightFields();
HighlightField title = highlightFields.get("title");
//获得原生未高亮的字段
Map<String, Object> sourceAsMap = fields.getSourceAsMap();
//如果高亮的字段不为空,就把普通字段替换成高亮字段
if(title != null){
Text[] texts = title.getFragments();
String n_title="";
for (Text text : texts) {
n_title+=text;
}
sourceAsMap.put("title",n_title);
}
list.add(sourceAsMap);
}
return list;
}
public AcknowledgedResponse delete() throws IOException {
//创建一个索引删除的命令
DeleteIndexRequest request = new DeleteIndexRequest("jd_index");
//执行删除索引的命令
AcknowledgedResponse response = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
return response;
}
}
HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8"/>
<title>林次月说Java-ES仿京东实战</title>
<link rel="stylesheet" th:href="@{/css/style.css}"/>
</head>
<body class="pg">
<div class="page" id="app">
<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 th:src="@{/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="keyword" type="text" autocomplete="off" value="dd" id="mq"
class="s-combobox-input" aria-haspopup="true">
</div>
</div>
<button type="submit" @click.prevent="searchkey()" 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="#"> 林次月说 </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">
<div class="product-iWrap">
<!--商品封面-->
<div class="productImg-wrap">
<a class="productImg">
<img :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>{{result.shop}} </span>
</div>
<!-- 成交信息 -->
<p class="productStatus">
<span style="color: chocolate">月成交<em>999笔</em></span>
<span>评价 <a>3</a></span>
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script th:src="@{/js/axios.min.js}"></script>
<script th:src="@{/js/vue.js}"></script>
<script>
new Vue({
el : '#app',
data:{
keyword :'', //搜索的关键字
results:[], //搜索的结果
},
methods:{
searchkey(){
var keyword=this.keyword;
axios.get('get/'+keyword+"/1/60").then(response=>{
this.results=response.data;
})
}
}
})
</script>
</body>
</html>
效果图