爬取京东手机商品信息(本人采用JAVA的MVEN工程)用时两天左右
最近喜欢上研究爬虫的问题了,发现还是很好用的,特别是这里运用了SpringBoot框架正是我最近在学的知识。
技术栈:SpringBoot、Mysql、JpaRepository、HttpClient、jsoup、commons-lang3
主要的文件结构如下
dao //做数据库操作
pojo //定义需要提取的元素与数据库对应
service //元素的存储、查询方法
task //需要完成的任务
util //定义Http连接的方式
通过上图可以看出爬虫的思路
首先创建连接,我这里通过HttpClient创建连接,其实Jsoup也可以为什么没有使用它呢,因为HttpClient支持线程管理等。
1、Util层
package cn.itcast.jd.util;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
/**
* @author kai
* @date 2020/5/21 12:03
*/
@Component
public class HttpUtils {
//建立连接池
private PoolingHttpClientConnectionManager cm;
public HttpUtils() {
//线程池,进行线程管理
this.cm =new PoolingHttpClientConnectionManager();
this.cm.setMaxTotal(100);
this.cm.setDefaultMaxPerRoute(10);
}
//根据请求地址下载页面数据
public String doGetHtml(String url){
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
HttpGet httpGet=new HttpGet(url);
httpGet.setConfig(this.getConfig());
//设置请求Request Headers中的User-Agent,告诉京东说我这是浏览器访问,您只需要做一个安静的美男子就够了
httpGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36");
CloseableHttpResponse response=null;
try {
response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode()==200){
if (response.getEntity()!=null){
String content = EntityUtils.toString(response.getEntity(), "utf8");
return content;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (response !=null){
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "";
}
//下载图片,返回名称
public String doGetImage(String url){
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(this.cm).build();
HttpGet httpGet=new HttpGet(url);
httpGet.setConfig(this.getConfig());
CloseableHttpResponse response=null;
try {
response