Java网络爬虫实操(3)
上一篇:Java網(wǎng)絡(luò)爬蟲實操(2)
本篇文章主要介紹NetDiscovery框架中pipeline模式的一些實際使用方法。
1) 什么是pipeline
pipeline是一種常見的算法模式,針對不斷循環(huán)的耗時任務(wù),如果要等一個循環(huán)結(jié)束后再輪到處理下一個任務(wù)的話,時間上有點浪費。
所以,把耗時任務(wù)拆分為幾個環(huán)節(jié),只要一個環(huán)節(jié)完成了,就可以輪到下一個任務(wù)的那個環(huán)節(jié)就馬上開始處理。不用等到這個耗時任務(wù)全部結(jié)束了才開始。
我認(rèn)為應(yīng)用在處理爬蟲程序獲取的數(shù)據(jù)上,非常合適。
2) pipeline在框架中的角色
從框架提供的原理圖上可以了解到,pipeline對象扮演的角色是什么:
- downloader對象訪問url
- 訪問成功后的page對象交給parser對象,進(jìn)行頁面的解析工作
- 把解析成果交給pipleline對象去按順序逐一處理,例如:去重、封裝、存儲、發(fā)消息等等
3) 目標(biāo)任務(wù)
任務(wù)步驟:
4) 創(chuàng)建pipeline對象
pipeline類:DownloadImage
package com.sinkinka.pipeline;import com.cv4j.netdiscovery.core.domain.ResultItems; import com.cv4j.netdiscovery.core.pipeline.Pipeline; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; import java.util.Map;public class DownloadImage implements Pipeline {@Overridepublic void process(ResultItems resultItems) {Map<String, Object> map = resultItems.getAll();for(String key : map.keySet()) {String filePath = "./temp/" + key + ".png";saveRemoteImage(map.get(key).toString(), filePath);}}private boolean saveRemoteImage(String imgUrl, String filePath) {InputStream in = null;OutputStream out = null;try {URL url = new URL(imgUrl);URLConnection connection = url.openConnection();connection.setConnectTimeout(5000);in = connection.getInputStream();byte[] bs = new byte[1024];int len;out = new FileOutputStream(filePath);while ((len = in.read(bs)) != -1) {out.write(bs, 0, len);}} catch(Exception e) {return false;} finally {try {out.flush();out.close();in.close();} catch(IOException e) {return false;}}return true;} } 復(fù)制代碼pipeline類:SaveImage
package com.sinkinka.pipeline;import com.cv4j.netdiscovery.core.domain.ResultItems; import com.cv4j.netdiscovery.core.pipeline.Pipeline; import com.safframework.tony.common.utils.Preconditions;import java.sql.*; import java.util.Map;public class SaveImage implements Pipeline {@Overridepublic void process(ResultItems resultItems) {Map<String, Object> map = resultItems.getAll();for(String key : map.keySet()) {System.out.println("2"+key);saveCompanyInfo(key, map.get(key).toString());}}private boolean saveCompanyInfo(String shortName, String logoUrl) {int insertCount = 0;Connection conn = getMySqlConnection();Statement statement = null;if(Preconditions.isNotBlank(conn)) {try {statement = conn.createStatement();String insertSQL = "INSERT INTO company(shortname, logourl) VALUES('"+shortName+"', '"+logoUrl+"')";insertCount = statement.executeUpdate(insertSQL);statement.close();conn.close();} catch(SQLException e) {return false;} finally {try{if(statement!=null) statement.close();}catch(SQLException e){}try{if(conn!=null) conn.close();}catch(SQLException e){}}}return insertCount > 0;}//演示代碼,不建議用于生產(chǎn)環(huán)境private Connection getMySqlConnection() {//使用的是mysql connector 5//數(shù)據(jù)庫:test 賬號/密碼: root/123456final String JDBC_DRIVER = "com.mysql.jdbc.Driver";final String DB_URL = "jdbc:mysql://localhost:3306/test";final String USER = "root";final String PASS = "123456";Connection conn = null;try {Class.forName(JDBC_DRIVER);conn = DriverManager.getConnection(DB_URL,USER,PASS);} catch(SQLException e) {return null;} catch(Exception e) {return null;}return conn;}}復(fù)制代碼5) 運行程序
Main類
package com.sinkinka;import com.cv4j.netdiscovery.core.Spider; import com.sinkinka.parser.LagouParser; import com.sinkinka.pipeline.DownloadImage; import com.sinkinka.pipeline.SaveImage;public class PipelineSpider {public static void main(String[] args) {String url = "https://xiaoyuan.lagou.com/";Spider.create().name("lagou").url(url).parser(new LagouParser()).pipeline(new DownloadImage()) //1. 首先,下載圖片到本地目錄.pipeline(new SaveImage()) //2. 然后,把圖片信息存儲到數(shù)據(jù)庫.run();} }復(fù)制代碼Parser類
package com.sinkinka.parser;import com.cv4j.netdiscovery.core.domain.Page; import com.cv4j.netdiscovery.core.domain.ResultItems; import com.cv4j.netdiscovery.core.parser.Parser; import com.cv4j.netdiscovery.core.parser.selector.Selectable; import java.util.List;public class LagouParser implements Parser {@Overridepublic void process(Page page) {ResultItems resultItems = page.getResultItems();List<Selectable> liList = page.getHtml().xpath("//li[@class='nav-logo']").nodes();for(Selectable li : liList) {String logoUrl = li.xpath("//img/@src").get();String companyShortName = li.xpath("//div[@class='company-short-name']/text()").get();resultItems.put(companyShortName, logoUrl);}} }復(fù)制代碼通過DownloadImage,保存到本地的圖片數(shù)據(jù):
通過SaveImage,存儲到數(shù)據(jù)庫里的數(shù)據(jù):
6) 總結(jié)
以上代碼簡單演示了pipeline模式的用法,記住一點,pipeline是有執(zhí)行順序的。在大量數(shù)據(jù)、高頻次的生產(chǎn)環(huán)境中再去體會pipeline模式的優(yōu)點吧。
下一篇:Java網(wǎng)絡(luò)爬蟲實操(4)
總結(jié)
以上是生活随笔為你收集整理的Java网络爬虫实操(3)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 高兴总结台式故障分析==方案
- 下一篇: vs里头文件写法