當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot集成Jsoup爬虫——三级列表
生活随笔
收集整理的這篇文章主要介紹了
SpringBoot集成Jsoup爬虫——三级列表
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
SpringBoot集成Jsoup爬蟲
爬取三級(jí)行政區(qū)域劃分,三級(jí)列表,存入數(shù)據(jù)庫中
前言
爬取獲取三級(jí)行政區(qū)域劃分,三級(jí)列表,根據(jù)三級(jí)劃分將區(qū)域代碼和城市存入數(shù)據(jù)庫中
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
一、爬蟲是什么?
網(wǎng)絡(luò)爬蟲為一個(gè)自動(dòng)提取網(wǎng)頁的程序,它為搜索引擎從萬維網(wǎng)上下載網(wǎng)頁,是搜索引擎的重要組成。傳統(tǒng)爬蟲從一個(gè)或若干初始網(wǎng)頁的URL開始,獲得初始網(wǎng)頁上的URL,在抓取網(wǎng)頁的過程中,不斷從當(dāng)前頁面上抽取新的URL放入隊(duì)列,直到滿足系統(tǒng)的一定停止條件。
將根據(jù)一定的搜索策略從隊(duì)列中選擇下一步要抓取的網(wǎng)頁URL,并重復(fù)上述過程,直到達(dá)到系統(tǒng)的某一條件時(shí)停止。另外,所有被爬蟲抓取的網(wǎng)頁將會(huì)被系統(tǒng)存貯,進(jìn)行一定的分析、過濾,并建立索引,以便之后的查詢和檢索。
二、使用步驟
1.引入庫
代碼如下(示例):
import crawl.JdbcUtil; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;2.爬蟲過程
代碼如下(示例):
String result = "";String charset = "UTF-8";try {URL url = new URL(strUrl);InputStream inputStream = url.openStream();InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName(charset));BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String s;StringBuffer stringBuffer = new StringBuffer();while ((s = bufferedReader.readLine()) != null) {stringBuffer.append(s);}result = stringBuffer.toString();} catch (Exception e) {System.out.println("錯(cuò)誤信息");e.printStackTrace();}return result; } Document document = Jsoup.parse(content);Elements element = document.select("table").select("tr");// 記錄省String province = "";// 記錄市String city = "";// 記錄編碼String code = "";String[] dataArr = new String[5];boolean flag = false;for (int i = 0; i < element.size(); i++) {String str = element.get(i).text();if (flag == true) {break;}dataArr = str.split(" ");// 從省開始判斷if (i < 3) {continue;}code = dataArr[0];if (code.endsWith("0000")) {// 省province = str;Map<String, List<String>> cityMap = new HashMap<>();countryMap.put(str, cityMap);} else if(code.endsWith("00") && !code.endsWith("0000")) {// 市city = str;Map<String, List<String>> cityMap = countryMap.get(province);cityMap.put(str, new ArrayList<String>());} else {// 區(qū)// 取出市Map<String, List<String>> cityMap = countryMap.get(province);// 取出區(qū)List<String> classifyList = cityMap.get(city);// 如果classify為null,沒有走市的if判斷,這是一個(gè)直轄市if (classifyList == null) {// 市為空,將北京省當(dāng)做市classifyList = new ArrayList<>();cityMap.put(city, classifyList);city = province;}classifyList.add(str);}if (str.startsWith("820000")) {flag = true;}}總結(jié)
知識(shí)點(diǎn),基本類型和包裝類型的值傳遞和引用傳遞。List,Map是引用傳遞,在別處進(jìn)行add或者put,Map和List中的數(shù)據(jù)都將跟著變。總結(jié)
以上是生活随笔為你收集整理的SpringBoot集成Jsoup爬虫——三级列表的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 智慧城市的互联网大脑架构图:大社交网络与
- 下一篇: python汉字长度_行中字符串的长度(