Java爬蟲 信息抓取的實現(xiàn)
今天公司有個需求,需要做一些指定網(wǎng)站查詢后的數(shù)據(jù)的抓取,于是花了點(diǎn)時間寫了個demo供演示使用。
思想很簡單:就是通過Java訪問的鏈接,然后拿到html字符串,然后就是解析鏈接等需要的數(shù)據(jù)。技術(shù)上使用Jsoup方便頁面的解析,當(dāng)然Jsoup很方便,也很簡單,一行代碼就能知道怎么用了:
Document doc = Jsoup.connect("http://www.oschina.net/") .data("query", "Java") // 請求參數(shù) .userAgent("I ' m jsoup") // 設(shè)置 User-Agent .cookie("auth", "token") // 設(shè)置 cookie .timeout(3000) // 設(shè)置連接超時時間 .post(); // 使用 POST 方法訪問 URL
下面介紹整個實現(xiàn)過程:
1、分析需要解析的頁面:
網(wǎng)址:http://www1.sxcredit.gov.cn/public/infocomquery.do?method=publicIndexQuery
頁面:
先在這個頁面上做一次查詢:觀察下請求的url,參數(shù),method等。
這里我們使用chrome內(nèi)置的開發(fā)者工具(快捷鍵F12),下面是查詢的結(jié)果:
我們可以看到url,method,以及參數(shù)。知道了如何或者查詢的URL,下面就開始代碼了,為了重用與擴(kuò)展,我定義了幾個類:
1、Rule.java用于指定查詢url,method,params等
package com.zhy.spider.rule; /** * 規(guī)則類 * * @author zhy * */ public class Rule { /** * 鏈接 */ private String url; /** * 參數(shù)集合 */ private String[] params; /** * 參數(shù)對應(yīng)的值 */ private String[] values; /** * 對返回的HTML,第一次過濾所用的標(biāo)簽,請先設(shè)置type */ private String resultTagName; /** * CLASS / ID / SELECTION * 設(shè)置resultTagName的類型,默認(rèn)為ID */ private int type = ID ; /** *GET / POST * 請求的類型,默認(rèn)GET */ private int requestMoethod = GET ; public final static int GET = 0 ; public final static int POST = 1 ; public final static int CLASS = 0; public final static int ID = 1; public final static int SELECTION = 2; public Rule() { } public Rule(String url, String[] params, String[] values, String resultTagName, int type, int requestMoethod) { super(); this.url = url; this.params = params; this.values = values; this.resultTagName = resultTagName; this.type = type; this.requestMoethod = requestMoethod; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String[] getParams() { return params; } public void setParams(String[] params) { this.params = params; } public String[] getValues() { return values; } public void setValues(String[] values) { this.values = values; } public String getResultTagName() { return resultTagName; } public void setResultTagName(String resultTagName) { this.resultTagName = resultTagName; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getRequestMoethod() { return requestMoethod; } public void setRequestMoethod(int requestMoethod) { this.requestMoethod = requestMoethod; } }
簡單說一下:這個規(guī)則類定義了我們查詢過程中需要的所有信息,方便我們的擴(kuò)展,以及代碼的重用,我們不可能針對每個需要抓取的網(wǎng)站寫一套代碼。
2、需要的數(shù)據(jù)對象,目前只需要鏈接,LinkTypeData.java
package com.zhy.spider.bean; public class LinkTypeData { private int id; /** * 鏈接的地址 */ private String linkHref; /** * 鏈接的標(biāo)題 */ private String linkText; /** * 摘要 */ private String summary; /** * 內(nèi)容 */ private String content; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getLinkHref() { return linkHref; } public void setLinkHref(String linkHref) { this.linkHref = linkHref; } public String getLinkText() { return linkText; } public void setLinkText(String linkText) { this.linkText = linkText; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
3、核心的查詢類:ExtractService.java
package com.zhy.spider.core; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.swing.plaf.TextUI; import org.jsoup.Connection; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.zhy.spider.bean.LinkTypeData; import com.zhy.spider.rule.Rule; import com.zhy.spider.rule.RuleException; import com.zhy.spider.util.TextUtil; /** * * @author zhy * */ public class ExtractService { /** * @param rule * @return */ public static List<LinkTypeData> extract(Rule rule) { // 進(jìn)行對rule的必要校驗 validateRule(rule); List<LinkTypeData> datas = new ArrayList<LinkTypeData>(); LinkTypeData data = null; try { /** * 解析rule */ String url = rule.getUrl(); String[] params = rule.getParams(); String[] values = rule.getValues(); String resultTagName = rule.getResultTagName(); int type = rule.getType(); int requestType = rule.getRequestMoethod(); Connection conn = Jsoup.connect(url); // 設(shè)置查詢參數(shù) if (params != null) { for (int i = 0; i < params.length; i++) { conn.data(params[i], values[i]); } } // 設(shè)置請求類型 Document doc = null; switch (requestType) { case Rule.GET: doc = conn.timeout(100000).get(); break; case Rule.POST: doc = conn.timeout(100000).post(); break; } //處理返回數(shù)據(jù) Elements results = new Elements(); switch (type) { case Rule.CLASS: results = doc.getElementsByClass(resultTagName); break; case Rule.ID: Element result = doc.getElementById(resultTagName); results.add(result); break; case Rule.SELECTION: results = doc.select(resultTagName); break; default: //當(dāng)resultTagName為空時默認(rèn)去body標(biāo)簽 if (TextUtil.isEmpty(resultTagName)) { results = doc.getElementsByTag("body"); } } for (Element result : results) { Elements links = result.getElementsByTag("a"); for (Element link : links) { //必要的篩選 String linkHref = link.attr("href"); String linkText = link.text(); data = new LinkTypeData(); data.setLinkHref(linkHref); data.setLinkText(linkText); datas.add(data); } } } catch (IOException e) { e.printStackTrace(); } return datas; } /** * 對傳入的參數(shù)進(jìn)行必要的校驗 */ private static void validateRule(Rule rule) { String url = rule.getUrl(); if (TextUtil.isEmpty(url)) { throw new RuleException("url不能為空!"); } if (!url.startsWith("http://")) { throw new RuleException("url的格式不正確!"); } if (rule.getParams() != null && rule.getValues() != null) { if (rule.getParams().length != rule.getValues().length) { throw new RuleException("參數(shù)的鍵值對個數(shù)不匹配!"); } } } }
4、里面用了一個異常類:RuleException.java
package com.zhy.spider.rule; public class RuleException extends RuntimeException { public RuleException() { super(); // TODO Auto-generated constructor stub } public RuleException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public RuleException(String message) { super(message); // TODO Auto-generated constructor stub } public RuleException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } }
5、最后是測試了:這里使用了兩個網(wǎng)站進(jìn)行測試,采用了不同的規(guī)則,具體看代碼吧
package com.zhy.spider.test; import java.util.List; import com.zhy.spider.bean.LinkTypeData; import com.zhy.spider.core.ExtractService; import com.zhy.spider.rule.Rule; public class Test { @org.junit.Test public void getDatasByClass() { Rule rule = new Rule( "http://www1.sxcredit.gov.cn/public/infocomquery.do?method=publicIndexQuery", new String[] { "query.enterprisename","query.registationnumber" }, new String[] { "興網(wǎng)","" }, "cont_right", Rule.CLASS, Rule.POST); List<LinkTypeData> extracts = ExtractService.extract(rule); printf(extracts); } @org.junit.Test public void getDatasByCssQuery() { Rule rule = new Rule("http://www.11315.com/search", new String[] { "name" }, new String[] { "興網(wǎng)" }, "div.g-mn div.con-model", Rule.SELECTION, Rule.GET); List<LinkTypeData> extracts = ExtractService.extract(rule); printf(extracts); } public void printf(List<LinkTypeData> datas) { for (LinkTypeData data : datas) { System.out.println(data.getLinkText()); System.out.println(data.getLinkHref()); System.out.println("***********************************"); } } }
輸出結(jié)果:
深圳市網(wǎng)興科技有限公司 http://14603257.11315.com *********************************** 荊州市興網(wǎng)公路物資有限公司 http://05155980.11315.com *********************************** 西安市全興網(wǎng)吧 # *********************************** 子長縣新興網(wǎng)城 # *********************************** 陜西同興網(wǎng)絡(luò)信息有限責(zé)任公司第三分公司 # *********************************** 西安高興網(wǎng)絡(luò)科技有限公司 # *********************************** 陜西同興網(wǎng)絡(luò)信息有限責(zé)任公司西安分公司 # ***********************************
最后使用一個Baidu新聞來測試我們的代碼:說明我們的代碼是通用的。
/** * 使用百度新聞,只設(shè)置url和關(guān)鍵字與返回類型 */ @org.junit.Test public void getDatasByCssQueryUserBaidu() { Rule rule = new Rule("http://news.baidu.com/ns", new String[] { "word" }, new String[] { "支付寶" }, null, -1, Rule.GET); List<LinkTypeData> extracts = ExtractService.extract(rule); printf(extracts); }
我們只設(shè)置了鏈接、關(guān)鍵字、和請求類型,不設(shè)置具體的篩選條件。
結(jié)果:有一定的垃圾數(shù)據(jù)是肯定的,但是需要的數(shù)據(jù)肯定也抓取出來了。我們可以設(shè)置Rule.SECTION,以及篩選條件進(jìn)一步的限制。
按時間排序 /ns?word=支付寶&ie=utf-8&bs=支付寶&sr=0&cl=2&rn=20&tn=news&ct=0&clk=sortbytime *********************************** x javascript:void(0) *********************************** 支付寶將聯(lián)合多方共建安全基金 首批投入4000萬 http://finance.ifeng.com/a/20140409/12081871_0.shtml *********************************** 7條相同新聞 /ns?word=%E6%94%AF%E4%BB%98%E5%AE%9D+cont:2465146414%7C697779368%7C3832159921&same=7&cl=1&tn=news&rn=30&fm=sd *********************************** 百度快照 http://cache.baidu.com/c?m=9d78d513d9d437ab4f9e91697d1cc0161d4381132ba7d3020cd0870fd33a541b0120a1ac26510d19879e20345dfe1e4bea876d26605f75a09bbfd91782a6c1352f8a2432721a844a0fd019adc1452fc423875d9dad0ee7cdb168d5f18c&p=c96ec64ad48b2def49bd9b780b64&newp=c4769a4790934ea95ea28e281c4092695912c10e3dd796&user=baidu&fm=sc&query=%D6%A7%B8%B6%B1%A6&qid=a400f3660007a6c5&p1=1 *********************************** OpenSSL漏洞涉及眾多網(wǎng)站 支付寶稱暫無數(shù)據(jù)泄露 http://tech.ifeng.com/internet/detail_2014_04/09/35590390_0.shtml *********************************** 26條相同新聞 /ns?word=%E6%94%AF%E4%BB%98%E5%AE%9D+cont:3869124100&same=26&cl=1&tn=news&rn=30&fm=sd *********************************** 百度快照 http://cache.baidu.com/c?m=9f65cb4a8c8507ed4fece7631050803743438014678387492ac3933fc239045c1c3aa5ec677e4742ce932b2152f4174bed843670340537b0efca8e57dfb08f29288f2c367117845615a71bb8cb31649b66cf04fdea44a7ecff25e5aac5a0da4323c044757e97f1fb4d7017dd1cf4&p=8b2a970d95df11a05aa4c32013&newp=9e39c64ad4dd50fa40bd9b7c5253d8304503c52251d5ce042acc&user=baidu&fm=sc&query=%D6%A7%B8%B6%B1%A6&qid=a400f3660007a6c5&p1=2 *********************************** 雅虎日本6月起開始支持支付寶付款 http://www.techweb.com.cn/ucweb/news/id/2025843 ***********************************
如果有什么不足,可以指出;如果覺得對你有用,頂一下~~哈哈
以上就是Java 爬蟲信息抓取的實例,后續(xù)繼續(xù)補(bǔ)充相關(guān)資料,謝謝大家對本站的支持!
- java編程實現(xiàn)簡單的網(wǎng)絡(luò)爬蟲示例過程
- Java 使用maven實現(xiàn)Jsoup簡單爬蟲案例詳解
- Java 實現(xiàn)網(wǎng)絡(luò)爬蟲框架詳細(xì)代碼
- 半小時實現(xiàn)Java手?jǐn)]網(wǎng)絡(luò)爬蟲框架(附完整源碼)
- 使用java實現(xiàn)網(wǎng)絡(luò)爬蟲
- Java實現(xiàn)的爬蟲抓取圖片并保存操作示例
- java實現(xiàn)一個簡單的網(wǎng)絡(luò)爬蟲代碼示例
- java實現(xiàn)網(wǎng)頁爬蟲的示例講解
- java實現(xiàn)簡單的爬蟲之今日頭條
- Java實現(xiàn)爬蟲
相關(guān)文章
使用Logback設(shè)置property參數(shù)方式
這篇文章主要介紹了使用Logback設(shè)置property參數(shù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03java利用遞歸調(diào)用實現(xiàn)樹形菜單的樣式
這篇文章主要給大家介紹了關(guān)于java利用遞歸調(diào)用實現(xiàn)樹形菜單樣式的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09springboot集成springCloud中g(shù)ateway時啟動報錯的解決
這篇文章主要介紹了springboot集成springCloud中g(shù)ateway時啟動報錯的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07Spring注解驅(qū)動擴(kuò)展原理BeanFactoryPostProcessor
這篇文章主要介紹了Spring注解驅(qū)動擴(kuò)展原理BeanFactoryPostProcessor,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03springboot3+r2dbc響應(yīng)式編程實踐
本文主要介紹了springboot3+r2dbc響應(yīng)式編程實踐,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-02-02啟動SpringBoot報JavaMail加載錯誤的原因分析和解決
這篇文章給大家介紹了啟動SpringBoot報JavaMail加載錯誤的原因分析和解決,文中通過代碼示例給出了詳細(xì)的原因分析和解決方法,對大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-01-01