Java中怎么实现一个网络爬虫
Java中怎么实现一个网络爬虫,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。
首先介绍每个类的功能:
DownloadPage.java的功能是下载此超链接的页面源代码.
FunctionUtils.java 的功能是提供不同的静态方法,包括:页面链接正则表达式匹配,获取URL链接的元素,判断是否创建文件,获取页面的Url并将其转换为规范的Url,截取网页网页源文件的目标内容。
HrefOfPage.java 的功能是获取页面源代码的超链接。
UrlDataHanding.java 的功能是整合各个给类,实现url到获取数据到数据处理类。
UrlQueue.java 的未访问Url队列。
VisitedUrlQueue.java 已访问过的URL队列。
下面介绍一下每个类的源代码:
DownloadPage.java 此类要用到HttpClient组件。
View Code package com.sreach.spider; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; public class DownloadPage { public static String getContentFormUrl(String url) { HttpClient client = new DefaultHttpClient(); HttpGet getHttp = new HttpGet(url); String content = null; HttpResponse response; try { response = client.execute(getHttp); HttpEntity entity = response.getEntity(); VisitedUrlQueue.addElem(url); if (entity != null) { content = EntityUtils.toString(entity); if (FunctionUtils.isCreateFile(url) && FunctionUtils.isHasGoalContent(content) != -1) { FunctionUtils.createFile(FunctionUtils .getGoalContent(content), url); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { client.getConnectionManager().shutdown(); } return content; } }
FunctionUtils.java 此类的方法均为static方法
View Code package com.sreach.spider; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FunctionUtils { private static String pat = "http://www\\.oschina\\.net/code/explore/.*/\\w+\\.[a-zA-Z]+"; private static Pattern pattern = Pattern.compile(pat); private static BufferedWriter writer = null; public static int depth = 0; public static String[] divUrl(String url) { return url.split("/"); } public static boolean isCreateFile(String url) { Matcher matcher = pattern.matcher(url); return matcher.matches(); } public static void createFile(String content, String urlPath) { String[] elems = divUrl(urlPath); StringBuffer path = new StringBuffer(); File file = null; for (int i = 1; i < elems.length; i++) { if (i != elems.length - 1) { path.append(elems[i]); path.append(File.separator); file = new File("D:" + File.separator + path.toString()); } if (i == elems.length - 1) { Pattern pattern = Pattern.compile("\\w+\\.[a-zA-Z]+"); Matcher matcher = pattern.matcher(elems[i]); if ((matcher.matches())) { if (!file.exists()) { file.mkdirs(); } String[] fileName = elems[i].split("\\."); file = new File("D:" + File.separator + path.toString() + File.separator + fileName[0] + ".txt"); try { file.createNewFile(); writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file))); writer.write(content); writer.flush(); writer.close(); System.out.println("创建文件成功"); } catch (IOException e) { e.printStackTrace(); } } } } } public static String getHrefOfInOut(String href) { String resultHref = null; if (href.startsWith("http://")) { resultHref = href; } else { if (href.startsWith("/")) { resultHref = "http://www.oschina.net" + href; } } return resultHref; } public static String getGoalContent(String content) { int sign = content.indexOf("<pre class=\""); String signContent = content.substring(sign); int start = signContent.indexOf(">"); int end = signContent.indexOf("</pre>"); return signContent.substring(start + 1, end); } public static int isHasGoalContent(String content) { return content.indexOf("<pre class=\""); } }
HrefOfPage.java 此类为获取页面的超链接
View Code package com.sreach.spider; public class HrefOfPage { public static void getHrefOfContent(String content) { System.out.println("开始"); String[] contents = content.split("<a href=\""); for (int i = 1; i < contents.length; i++) { int endHref = contents[i].indexOf("\""); String aHref = FunctionUtils.getHrefOfInOut(contents[i].substring( , endHref)); if (aHref != null) { String href = FunctionUtils.getHrefOfInOut(aHref); if (!UrlQueue.isContains(href) && href.indexOf("/code/explore") != -1 && !VisitedUrlQueue.isContains(href)) { UrlQueue.addElem(href); } } } System.out.println(UrlQueue.size() + "--抓取到的连接数"); System.out.println(VisitedUrlQueue.size() + "--已处理的页面数"); } }
UrlDataHanding.java 此类主要是从未访问队列中获取url,下载页面,分析url,保存已访问url等操作,实现Runnable接口
View Code package com.sreach.spider; public class UrlDataHanding implements Runnable { public void dataHanding(String url) { HrefOfPage.getHrefOfContent(DownloadPage.getContentFormUrl(url)); } public void run() { while(!UrlQueue.isEmpty()) { dataHanding(UrlQueue.outElem()); } } }
UrlQueue.java 此类主要是用来存放未访问的URL队列
View Code package com.sreach.spider; import java.util.LinkedList; public class UrlQueue { public static LinkedList<String> urlQueue = new LinkedList<String>(); public static final int MAX_SIZE = 10000; public synchronized static void addElem(String url) { urlQueue.add(url); } public synchronized static String outElem() { return urlQueue.removeFirst(); } public synchronized static boolean isEmpty() { return urlQueue.isEmpty(); } public static int size() { return urlQueue.size(); } public static boolean isContains(String url) { return urlQueue.contains(url); } }
VisitedUrlQueue.java 主要是保存已访问过的URL,使用HashSet来保存,主要是考虑到每个访问过的URL是不同。HashSet刚好符合这个要求
View Code package com.sreach.spider; import java.util.HashSet; public class VisitedUrlQueue { public static HashSet<String> visitedUrlQueue = new HashSet<String>(); public synchronized static void addElem(String url) { visitedUrlQueue.add(url); } public synchronized static boolean isContains(String url) { return visitedUrlQueue.contains(url); } public synchronized static int size() { return visitedUrlQueue.size(); } }
Test.java 此类为测试类
View Code import java.sql.SQLException; import com.sreach.spider.UrlDataHanding; import com.sreach.spider.UrlQueue; public class Test { public static void main(String[] args) throws SQLException { String url = "http://www.oschina.net/code/explore/achartengine/client/AndroidManifest.xml"; String url1 = "http://www.oschina.net/code/explore"; String url2 = "http://www.oschina.net/code/explore/achartengine"; String url3 = "http://www.oschina.net/code/explore/achartengine/client"; UrlQueue.addElem(url); UrlQueue.addElem(url1); UrlQueue.addElem(url2); UrlQueue.addElem(url3); UrlDataHanding[] url_Handings = new UrlDataHanding[10]; for(int i = 0 ; i < 10 ; i++) { url_Handings[i] = new UrlDataHanding(); new Thread(url_Handings[i]).start(); } } }
关于Java中怎么实现一个网络爬虫问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注编程网行业资讯频道了解更多相关知识。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341