iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Java中怎么实现一个网络爬虫
  • 644
分享到

Java中怎么实现一个网络爬虫

2023-06-17 10:06:06 644人浏览 八月长安
摘要

Java中怎么实现一个网络爬虫,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。首先介绍每个类的功能:DownloadPage.java的功能是下载此超链接的页面源代码.Fun

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中怎么实现一个网络爬虫问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注编程网精选频道了解更多相关知识。

--结束END--

本文标题: Java中怎么实现一个网络爬虫

本文链接: https://www.lsjlt.com/news/288350.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Java中怎么实现一个网络爬虫
    Java中怎么实现一个网络爬虫,针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。首先介绍每个类的功能:DownloadPage.java的功能是下载此超链接的页面源代码.Fun...
    99+
    2023-06-17
  • 怎么在python中使用selenium实现一个网络爬虫
    本篇文章为大家展示了怎么在python中使用selenium实现一个网络爬虫,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。Python主要用来做什么Python主要应用于:1、Web开发;2、数据科...
    99+
    2023-06-08
  • 怎么在hadoop中实现一个java爬虫
    今天就跟大家聊聊有关怎么在hadoop中实现一个java爬虫,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。需要用到Cygwin:一个在windows平台上运行的类UNIX模拟环境,直...
    99+
    2023-05-31
    java ava hadoop
  • java实现一个简单的网络爬虫代码示例
    目前市面上流行的爬虫以python居多,简单了解之后,觉得简单的一些页面的爬虫,主要就是去解析目标页面(html)。那么就在想,java有没有用户方便解析html页面呢?找到了一个jsoup包,一个非常方便解析html的工具呢。使用方式也非...
    99+
    2023-05-30
    网络爬虫 java jsoup
  • 怎么用Scrapy构建一个网络爬虫
    这篇文章主要讲解了“怎么用Scrapy构建一个网络爬虫”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用Scrapy构建一个网络爬虫”吧!我们来看下Scrapy怎么做到这些功能的。首先准备...
    99+
    2023-06-03
  • 利用java怎么实现一个网页爬虫功能
    利用java怎么实现一个网页爬虫功能?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。爬虫实现原理网络爬虫基本技术处理网络爬虫是数据采集的一种方法,实际项目开发中,通过爬虫做数...
    99+
    2023-05-31
    java ava
  • 怎么在java中实现一个多线程爬虫
    怎么在java中实现一个多线程爬虫?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。Java可以用来干什么Java主要应用于:1. web开发;2. Android...
    99+
    2023-06-14
  • node中怎么实现一个http小爬虫
    这篇文章给大家介绍node中怎么实现一个http小爬虫,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。爬取Node.js 教程首页的所有数据建立node-http.js,其中代码如下,代...
    99+
    2024-04-02
  • nodejs中怎么实现一个多页面爬虫
    这期内容当中小编将会给大家带来有关nodejs中怎么实现一个多页面爬虫,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。request 用于请求地址和快速下载图片流。 htt...
    99+
    2024-04-02
  • Java 实现网络爬虫框架详细代码
    目录Java 实现网络爬虫框架一、每个类的功能介绍二、每个类的源代码Java 实现网络爬虫框架 最近在做一个搜索相关的项目,需要爬取网络上的一些链接存储到索引库中,虽然有很多开源的强...
    99+
    2024-04-02
  • 如何实现Java手撸网络爬虫框架
    这篇文章主要为大家展示了“如何实现Java手撸网络爬虫框架”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何实现Java手撸网络爬虫框架”这篇文章吧。首先介绍每个类的功能:DownloadPag...
    99+
    2023-06-20
  • 在Java中使用Jsoup实现一个爬虫功能
    在Java中使用Jsoup实现一个爬虫功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。 Java 爬虫工具Jsoup详解Jsoup是一款 Java 的 HTML 解...
    99+
    2023-05-31
    java 爬虫 jsoup
  • 使用C++编写一个DHT爬虫,实现从DHT网络爬取BT种子
    以下是一个简单的使用C++编写的DHT爬虫,以从DHT网络中爬取BT种子:```cpp#include #include #incl...
    99+
    2023-10-12
    C++
  • 利用JAVA实现一个多线程爬虫
    利用JAVA实现一个多线程爬虫?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。JAVA 多线程爬虫实例详解前言以前喜欢Python的爬虫是出于他的简洁,但到了后期...
    99+
    2023-05-31
    java 多线程 爬虫
  • 怎么在python中使用feapde实现一个爬虫
    这篇文章给大家介绍怎么在python中使用feapde实现一个爬虫,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。python是什么意思Python是一种跨平台的、具有解释性、编译性、互动性和面向对象的脚本语言,其最初的...
    99+
    2023-06-14
  • 打造一个健壮高效的网络爬虫
    以下内容转自爬虫界大佬崔庆才的文章,传送门   整个分享的主题叫做《健壮高效的网络爬虫》,本次分享从抓取、解析、存储、反爬、加速五个方面介绍了利用 Python 进行网络爬虫开发的相关知识点和技巧,介绍了不同场景下如何采取不同措施高效地进...
    99+
    2023-01-30
    爬虫 高效 健壮
  • 网站怎么阻止网络爬虫
    这篇文章主要为大家展示了“网站怎么阻止网络爬虫”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“网站怎么阻止网络爬虫”这篇文章吧。两种主要方法可以阻止爬虫:1.屏蔽它的 IP 地址。收集爬虫的所有 ...
    99+
    2023-06-20
  • 怎么使用Java IO流和网络制作一个简单的图片爬虫
    这篇文章主要介绍“怎么使用Java IO流和网络制作一个简单的图片爬虫”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“怎么使用Java IO流和网络制作一个简单的图片爬虫”文章能帮助大家解决问题。Ja...
    99+
    2023-07-05
  • Java语言怎么实现爬虫
    这篇文章给大家分享的是有关Java语言怎么实现爬虫的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。为什么我们要爬取数据在大数据时代,我们要获取更多数据,就要进行数据的挖掘、分析、筛选,比如当我们做一个项目的时候,需...
    99+
    2023-06-22
  • 怎么使用nodejs实现一个简单的网页爬虫功能
    这篇文章主要介绍了怎么使用nodejs实现一个简单的网页爬虫功能,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。网页源码  使用http.get()方法获取网页源码,以hao1...
    99+
    2023-06-06
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作