技术标签: 网络爬虫 程序员进阶 后端开发 数据采集 精通Java系列
大家好,我是冰河~~
最近在做一个搜索相关的项目,需要爬取网络上的一些链接存储到索引库中,虽然有很多开源的强大的爬虫框架,但本着学习的态度,自己写了一个简单的网络爬虫,以便了解其中的原理。今天,就为小伙伴们分享下这个简单的爬虫程序!!
小伙伴们如果觉得文章不错,点赞、收藏、评论,分享走一起呀,记得给冰河来个一键三连~~
说干就干,我们开始吧!
首先介绍每个类的功能:
DownloadPage.java的功能是下载此超链接的页面源代码.
FunctionUtils.java 的功能是提供不同的静态方法,包括:页面链接正则表达式匹配,获取URL链接的元素,判断是否创建文件,获取页面的Url并将其转换为规范的Url,截取网页网页源文件的目标内容。
HrefOfPage.java 的功能是获取页面源代码的超链接。
UrlDataHanding.java 的功能是整合各个给类,实现url到获取数据到数据处理类。
UrlQueue.java 的未访问Url队列。
VisitedUrlQueue.java 已访问过的URL队列。
下面介绍一下每个类的源代码:
DownloadPage.java 此类要用到HttpClient组件。
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;
/**
* @author binghe
*/
public class DownloadPage {
/**
* 根据URL抓取网页内容
*
* @param url
* @return
*/
public static String getContentFormUrl(String url) {
/* 实例化一个HttpClient客户端 */
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方法
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;
/**
* @author binghe
*/
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;
/**
* 以"/"来分割URL,获得超链接的元素
*
* @param url
* @return
*/
public static String[] divUrl(String url) {
return url.split("/");
}
/**
* 判断是否创建文件
*
* @param url
* @return
*/
public static boolean isCreateFile(String url) {
Matcher matcher = pattern.matcher(url);
return matcher.matches();
}
/**
* 创建对应文件
*
* @param content
* @param urlPath
*/
public static void createFile(String content, String urlPath) {
/* 分割url */
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();
}
}
}
}
}
/**
* 获取页面的超链接并将其转换为正式的A标签
*
* @param href
* @return
*/
public static String getHrefOfInOut(String href) {
/* 内外部链接最终转化为完整的链接格式 */
String resultHref = null;
/* 判断是否为外部链接 */
if (href.startsWith("http://")) {
resultHref = href;
} else {
/* 如果是内部链接,则补充完整的链接地址,其他的格式忽略不处理,如:a href="#" */
if (href.startsWith("/")) {
resultHref = "http://www.oschina.net" + href;
}
}
return resultHref;
}
/**
* 截取网页网页源文件的目标内容
*
* @param content
* @return
*/
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);
}
/**
* 检查网页源文件中是否有目标文件
*
* @param content
* @return
*/
public static int isHasGoalContent(String content) {
return content.indexOf("<pre class=\"");
}
}
HrefOfPage.java 此类为获取页面的超链接
package com.sreach.spider;
/**
* @author binghe
*
*/
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(
0, 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接口
package com.sreach.spider;
/**
* @author binghe
*
*/
public class UrlDataHanding implements Runnable {
/**
* 下载对应页面并分析出页面对应的URL放在未访问队列中。
*
* @param url
*/
public void dataHanding(String url) {
HrefOfPage.getHrefOfContent(DownloadPage.getContentFormUrl(url));
}
public void run() {
while (!UrlQueue.isEmpty()) {
dataHanding(UrlQueue.outElem());
}
}
}
UrlQueue.java 此类主要是用来存放未访问的URL队列
package com.sreach.spider;
import java.util.LinkedList;
/**
* @author binghe
*
*/
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刚好符合这个要求
package com.sreach.spider;
import java.util.HashSet;
/**
* 已访问url队列
* @author binghe
*
*/
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 此类为测试类
import java.sql.SQLException;
import com.sreach.spider.UrlDataHanding;
import com.sreach.spider.UrlQueue;
/**
* @author binghe
*
*/
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();
}
}
}
说明一下:由于我抓取的是针对oschina的,所以里面的url正则表达式不适合其他网站,需要自己修改一下。你也可以写成xml来配置。
如果你想进大厂,想升职加薪,或者对自己现有的工作比较迷茫,都可以私信我交流,希望我的一些经历能够帮助到大家~~
推荐阅读:
好了,今天就到这儿吧,小伙伴们点赞、收藏、评论,一键三连走起呀,我是冰河,我们下期见~~
文章浏览阅读10w+次,点赞3次,收藏15次。本资料整理自 Kaggle上的Spooky NLP and Topic Modelling tutorialimport base64import numpy as npimport pandas as pd#Plotly imports 一种可视化工具import plotly.offline as pypy.init_notebook_mode(connected=True)..._~3abb31fzgf~
文章浏览阅读150次。分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴! &
文章浏览阅读2.5k次。SQLyog Community是SQLyog数据库管理软件的社区版本,它提供了图形化的数据库管理界面,拥有强大的数据库管理功能,便捷的操作让维护人员轻松的管理数据,需要的朋友快来下载使用吧。SQLyog Community介绍SQLyog 是一个简洁高效功能强大的,GUI 图形化用户管理接口的 MySQL 数据库管理工具。使用 SQLyog 可以让您从世界的任何角落透过网络来维护远端的 MySQ..._sqlyog社区版下载
文章浏览阅读6.8k次,点赞2次,收藏8次。第一种Transactional注解标注方法修饰符为非public时,@Transactional注解将会不起作用。第二种在类内部调用调用类内部@Transactional标注的方法。这种情况下也会导致事务不开启。既然事务管理是基于动态代理对象的代理逻辑实现的,那么如果在类内部调用类内部的事务方法,这 个调用事务方法的过程并不是通过代理对象来调用的,而是直接通过this对象来调用方法,绕过的代理对 象,肯定就是没有代理逻辑了。解决方法1.可以在service层 注入自己 用自己调用方_transactional注解失效
文章浏览阅读559次。接口耦合优化与灾难控制
文章浏览阅读1.9k次,点赞4次,收藏2次。laravel7 版本移除了 auth,大家都知道以前版本是直接使用php artisan make:auth就可以使用,但是这版本不行了,那么要怎么弄呢?今天和大家说一下具体步骤。Laravel7 的 laravel/ui 包提供了一种快速方法,可以使用一些简单的命令来支持你进行身份验证所需的所有路由和视图:安装依赖包laravel/ui直接使用命令进行安装composer require laravel/ui创建auth脚手架直接使用命令进行创建#注意这里的v._laravel7.x 如何使用自定义的auth进行身份验证
文章浏览阅读3.3k次,点赞3次,收藏33次。@[TOC](Maix Bit(K210) SDK )Maix Bit 开发板Kendryte IDE开发环境实现功能,在串口助手输入字符,通过Maix Bit回显在串口。 嵌入式应用通常要求一个简单的并且占用系统资源少的方法来传输数据。通用异步收发传输器(UART)即可以满足这些要求,它能够灵活地与外部设备进行全双工数据交换。1、使用API简介相关开发文档下载请看:https://blog.csdn.net/weixin_45488643/article/details/10923901_k210串口如何发送到电脑端接收
文章浏览阅读1.2k次。配置中进行如下调整:其实就是在在yarn-site.xm中添加yarn.resourcemanager.scheduler.class,修改成容量调度器:<property> <name>yarn.resourcemanager.scheduler.class</name> <value>org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacitySche_cdh6.3 配置capacity调度
文章浏览阅读3.1k次。回lz:1.我用过的linux,一般几种:A) ubuntu类型的,就一张iso的那种,就是安装盘B) 类似redhat 、fedora、centos等,都是>5cd的但是就我的看法,应该第二张盘没有用你这种盘我没见到过,不好说2. 和windows一样,都要驱动,只不过是linux在安装的时候自动识别,如果可以识别,那么就没问题,如果不能识别,到相应的硬件厂商寻找第三方驱动。不过一般网卡,比如tplink的,intel的,都自带的。当然,如果你的网卡芯片特别独特,那么就不好说了3.如果不能上网,看看_安装linux内核后很多驱动都不用了
文章浏览阅读514次。CNN主要用于图像处理任务中的特征提取,通过卷积核对输入数据进行卷积操作,得到一系列特征图。具体来说,我们将多维数据视为三维矩阵,CNN对每个时间步的矩阵进行卷积提取特征,得到一系列的特征图。以上就是本文提出的基于CNN-GRU的多维数据预测算法和相应的Matlab实现代码。在实际应用中,我们可以根据自己的数据特点调整卷积核大小、卷积核数、池化大小等参数,以获得更好的预测效果。本文提出了一种基于CNN-GRU结构的多维数据预测算法,并提供了相应的Matlab代码。_三维数据用cnn预测
文章浏览阅读7.6k次,点赞3次,收藏11次。前言Blender本身并不直接支持Gif动画的导出,下面是几种网上常见解决方案:使用Bligify插件: 网上有介绍这个插件的,但是该插件最后一次更新已经是2019年7月了,老王觉得以Blender的更新速度,这个插件的时效性可能不是很稳。????导出视频,使用FFMpeg转换: FFMpeg是个开源免费的格式转换神器,但是它是没有图形界面的,使用起来略有不便。????导出视频,使用AVS Video Converter转换: 稳定且足够傻瓜。????AVS Video Con_blender导出gif
文章浏览阅读2.9k次。厦门四六开科技给大家讲讲如何用微信web开发者工具测试调试并打包上传小程序,其实还是很简单的,这个教程针对小白,大神请直接略过。一、下载并安装软件(根据自己电脑实际情况选择版本安装)如何用微信开发者工具新建小程序项目并打包上传教程二、新建一个小程序项目双击打开桌面图标,打开新建一个小程序项目,这里的项目目录填写春哥给你的小程序压缩包解压后的路径,选择即可,Appid填写自己的,项目名称随便填,如下图:如何用微信开发者工具新建小程序项目并打包上传教程三、修改配置文件,对接上自己的网址(这个前提自_微信模拟器可以调试文件上传吗