springboot之簡(jiǎn)易爬蟲demo

需求:

使用httpClient 爬: 白居易的<琵琶行>

? ? ? http://www.shicimingju.com/chaxun/list/4059.html

? ? ? 要求:輸入上述url 返回白居易的琵琶行

效果如下:?


java爬蟲

一、該項(xiàng)目使用springboot的多組件方式,即需要一個(gè)前端和后端提供數(shù)據(jù)的api接口。項(xiàng)目目錄結(jié)構(gòu)如下:

爬蟲項(xiàng)目目錄結(jié)構(gòu)

二、思路: 獲取前端的url內(nèi)容地址, 通過HttpClients獲取整個(gè)頁(yè)面內(nèi)容,再通過Jsoup進(jìn)行解析獲取相關(guān)標(biāo)簽下面的內(nèi)容。

三、maven需要的依賴及版本

<parent> <groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.1.3.RELEASE</version>

<relativePath/>

</parent><groupId>com.alibaba</groupId>

<artifactId>httpclient</artifactId>

<version>1.0.0</version><properties>

<java.version>1.8</java.version>

</properties><dependencies>

<dependency>

<groupId>org.apache.httpcomponents</groupId>

<artifactId>httpclient</artifactId>

<version>4.5.8</version>

</dependency>

<dependency> <groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.jsoup</groupId>

<artifactId>jsoup</artifactId>

<version>1.7.3</version>

</dependency>

<!--lombok-->

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

</dependency>

</dependencies>

controller:


controller

兩個(gè)工具類

public class HttpClientUtil {

public static StringgetHtml(String url) {

//1.生成httpclient,相當(dāng)于該打開一個(gè)瀏覽器

? ? ? ? CloseableHttpClient httpClient = HttpClients.createDefault();

? ? ? ? CloseableHttpResponse response =null;

? ? ? ? //2.創(chuàng)建get請(qǐng)求,相當(dāng)于在瀏覽器地址欄輸入 網(wǎng)址

//? ? ? ? HttpGet request = new HttpGet("http://www.shicimingju.com/chaxun/list/4059.html");

? ? ? ? HttpGet request =new HttpGet(url);

? ? ? ? try {

//3.執(zhí)行g(shù)et請(qǐng)求,相當(dāng)于在輸入地址欄后敲回車鍵

? ? ? ? ? ? response = httpClient.execute(request);

? ? ? ? ? ? //4.判斷響應(yīng)狀態(tài)為200,進(jìn)行處理

? ? ? ? ? ? if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

//5.獲取響應(yīng)內(nèi)容

? ? ? ? ? ? ? ? HttpEntity httpEntity = response.getEntity();

? ? ? ? ? ? ? ? String html = EntityUtils.toString(httpEntity, "utf-8");

? ? ? ? ? ? ? ? // Jsoup 解析網(wǎng)頁(yè)數(shù)據(jù)

? ? ? ? ? ? ? ? Document document = Jsoup.parse(html);

? ? ? ? ? ? ? ? // 獲取目標(biāo)內(nèi)容

? ? ? ? ? ? ? ? Elements item_content = document.getElementsByClass("item_content");

//? ? ? ? ? ? ? ? String text = item_content.text();

? ? ? ? ? ? ? ? return item_content.toString();

? ? ? ? ? ? }else {

//如果返回狀態(tài)不是200,比如404(頁(yè)面不存在)等,根據(jù)情況做處理,這里略

? ? ? ? ? ? ? ? System.out.println("返回狀態(tài)不是200");

? ? ? ? ? ? ? ? System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));

? ? ? ? ? ? ? ? return "不是200";

? ? ? ? ? ? }

}catch (ClientProtocolException e) {

e.printStackTrace();

? ? ? ? }catch (IOException e) {

e.printStackTrace();

? ? ? ? }finally {

//6.關(guān)閉

? ? ? ? ? ? HttpClientUtils.closeQuietly(response);

? ? ? ? ? ? HttpClientUtils.closeQuietly(httpClient);

? ? ? ? }

return "請(qǐng)輸入正確url地址";

? ? }

}



@Setter

@Getter

@NoArgsConstructor

public class JsonResult {

public static final int CODE_SUCCESS =200;

? ? public static final StringMSG_SUCCESS ="操作成功";

? ? public static final int CODE_NOLOGIN =401;

? ? public static final StringMSG_NOLOGIN ="請(qǐng)先登錄";

? ? public static final int CODE_ERROR =500;

? ? public static final StringMSG_ERROR ="系統(tǒng)異常,請(qǐng)聯(lián)系管理員";

? ? public static final int CODE_ERROR_PARAM =501; // 參數(shù)異常

? ? private int code; // 用來(lái)區(qū)分不同的結(jié)果, 不是true或false

? ? private Stringmsg; // 處理操作, 還要攜帶的數(shù)據(jù)

? ? private T data;

? ? public JsonResult(int code, String msg, T data){

this.code = code;

? ? ? ? this.msg = msg;

? ? ? ? this.data = data;

? ? }

public static JsonResultsuccess(T data){

return new JsonResult(CODE_SUCCESS, MSG_SUCCESS, data);

? ? }

public static JsonResultsuccess(){

return new JsonResult(CODE_SUCCESS, MSG_SUCCESS, null);

? ? }

public static JsonResulterror(int code, String msg, T data){

return new JsonResult(code, msg, data);

? ? }

public static JsonResultdefaultError(){

return new JsonResult(CODE_ERROR, MSG_ERROR, null);

? ? }

public static JsonResultnoLogin() {

return new JsonResult(CODE_NOLOGIN, MSG_NOLOGIN, null);

? ? }

}



主方法:

@SpringBootApplication

public class WebSiteAppimplements WebMvcConfigurer {

//跨域訪問

? ? @Bean

? ? public WebMvcConfigurercorsConfigurer() {

return new WebMvcConfigurer() {

@Override

? ? ? ? ? ? //重寫父類提供的跨域請(qǐng)求處理的接口

? ? ? ? ? ? public void addCorsMappings(CorsRegistry registry) {

//添加映射路徑

? ? ? ? ? ? ? ? registry.addMapping("/**")

//放行哪些原始域

? ? ? ? ? ? ? ? ? ? ? ? .allowedOrigins("*")

//是否發(fā)送Cookie信息

? ? ? ? ? ? ? ? ? ? ? ? .allowCredentials(true)

//放行哪些原始域(請(qǐng)求方式)

? ? ? ? ? ? ? ? ? ? ? ? .allowedMethods("GET", "POST", "PUT", "DELETE","OPTIONS")

//放行哪些原始域(頭部信息)

? ? ? ? ? ? ? ? ? ? ? ? .allowedHeaders("*")

//暴露哪些頭部信息(因?yàn)榭缬蛟L問默認(rèn)不能獲取全部頭部信息)

? ? ? ? ? ? ? ? ? ? ? ? .exposedHeaders("Header1", "Header2");

? ? ? ? ? ? }

};

? ? }

public static void main(String[] args) {

SpringApplication.run(WebSiteApp.class, args);

? ? }

}



配置端口: application.properties

server.port=8081



前端用到j(luò)query的插件:

<!DOCTYPE html>

<html lang="en">

? ? <meta charset="UTF-8">

? ? <title>Title

? ? <script src="../jquery/jquery.js">

? ? ? ? $(function () {

$('#url').blur(function () {

// 獲取url地址

? ? ? ? ? ? ? ? var url =$("#url").val();

? ? ? ? ? ? ? ? console.log(url);

? ? ? ? ? ? ? ? // 提交表單

? ? ? ? ? ? ? ? $.get('http://localhost:8081/htmlclient/list',{url: url}, function (data) {

? ? ? ? ? ? ? ? ? ? console.log(data.data);

? ? ? ? ? ? ? ? ? ? if (data.code ==200){

// 追加內(nèi)容

? ? ? ? ? ? ? ? ? ? ? ? $("#item_content").append(data.data)

}

})

})

})

<form id="myForm">

? ? <table border="1" cellspacing="0">

? ? ? ? ? ? ? ? ? ? url:<input type="text" id="url">

? ? ? ? ? ? ? ? <div class="item_content" id="item_content">

</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容