`
flylynne
  • 浏览: 363317 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

简单网络爬虫基础功能

    博客分类:
  • JAVA
 
阅读更多
package com.common;

//http://127.0.0.1:8080/zz3zcwbwebhome/index.jsp 
//http://127.0.0.1:8080/zz3zcwbwebhome/reply.jsp 

import java.util.*;
import java.net.*;
import java.io.*;
import java.util.regex.*;

public class SearchCrawler implements Runnable {
	// error message list 错误信息
	ArrayList<String> errorList = new ArrayList<String>();
	// search result 搜索到的结果
	ArrayList<String> resultList = new ArrayList<String>();
	String startUrl;// base URL for searching 开始搜索的起点
	String searchString;// searching target String 要搜索的字符串(英文)
	int maxUrl;// 最大处理的url数
	boolean caseSensitive = false; // Case Sensitivity 是否区分大小写
	boolean limitHost = false; // limit in host 是否在限制的主机内搜索
	HashMap<String, ArrayList<String>> disallowListCache = new HashMap<String, ArrayList<String>>();

	public SearchCrawler() {
	}

	public SearchCrawler(String startUrl, int maxUrl, String searchString) {
		this.startUrl = startUrl;
		this.maxUrl = maxUrl;
		this.searchString = searchString;
	}

	public ArrayList<String> getResultList() {
		return resultList;
	}

	// start crawler thread 启动搜索线程
	public void run() {
		crawl(startUrl, maxUrl, searchString, limitHost, caseSensitive);
	}

	// check URL format 检测URL格式
	private URL verifyUrl(String url) {
		// only deal with HTTP URL 只处理HTTP URLs
		if (!url.toLowerCase().startsWith("http://"))
			return null;

		URL verifiedUrl = null;
		try {
			verifiedUrl = new URL(url);
		} catch (Exception e) {
			return null;
		}
		return verifiedUrl;
	}

	// check accessing URL 检测robot是否允许访问给出的URL.
	private boolean isRobotAllowed(URL urlToCheck) {
		// get host URL 获取给出URL的主机
		String host = urlToCheck.getHost().toLowerCase();
		// not allow to search URL cache from host 获取主机不允许搜索的URL缓存
		ArrayList<String> disallowList = disallowListCache.get(host);

		// if no cache,download and cache 如果还没有缓存,下载并缓存。
		if (disallowList == null) {
			disallowList = new ArrayList<String>();
			try {
				URL robotsFileUrl = new URL("http://" + host + "/robots.txt");
				BufferedReader reader = new BufferedReader(new InputStreamReader(robotsFileUrl.openStream()));

				// read robot file and create not allow URL list
				// 读robot文件,创建不允许访问的路径列表。
				String line = "";
				String disallowPath = "";
				while ((line = reader.readLine()) != null) {
					// exists disallow 是否包含"Disallow:
					if (line.indexOf("Disallow:") == 0) {
						// get not allow access URL 获取不允许访问路径
						disallowPath = line.substring("Disallow:".length());

						// check comments 检查是否有注释。
						int commentIndex = disallowPath.indexOf("#");
						if (commentIndex != -1) {
							// get comments
							disallowPath = disallowPath.substring(0, commentIndex);
						}
						disallowPath = disallowPath.trim();// trim blank
						disallowList.add(disallowPath);
					}
				}
				disallowListCache.put(host, disallowList);
			} catch (Exception e) {
				return true;
			}
		}

		String file = urlToCheck.getFile();
		for (int i = 0; i < disallowList.size(); i++) {
			String disallow = disallowList.get(i);
			if (file.startsWith(disallow)) {
				return false;
			}
		}
		return true;
	}

	// remove www from URL 从URL中去掉"www"
	private String removeWwwFromUrl(String url) {
		int index = url.indexOf("://www.");
		if (index != -1) {
			return url.substring(0, index + 3) + url.substring(index + 7);
		}

		return (url);
	}

	// parse page and find link 解析页面并找出链接
	private ArrayList<String> retrieveLinks(URL pageUrl, String pageContents, HashSet crawledList, boolean limitHost) {
		// use regex to match 用正则表达式编译链接的匹配模式。
		Pattern p = Pattern.compile("<a\\s+href\\s*=\\s*\"?(.*?)[\"|>]", Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(pageContents);

		ArrayList<String> linkList = new ArrayList<String>();
		while (m.find()) {
			String link = m.group(1).trim();

			if (link.length() < 1) {
				continue;
			}

			// jump to page link 跳过链到本页面内链接。
			if (link.charAt(0) == '#') {
				continue;
			}

			if (link.indexOf("mailto:") != -1) {
				continue;
			}

			if (link.toLowerCase().indexOf("javascript") != -1) {
				continue;
			}

			if (link.indexOf("://") == -1) {
				if (link.charAt(0) == '/') {// deal with absolute path 处理绝对地
					link = "http://" + pageUrl.getHost() + ":" + pageUrl.getPort() + link;
				} else {
					String file = pageUrl.getFile();
					if (file.indexOf('/') == -1) {// deal with relative path
													// 处理相对地址
						link = "http://" + pageUrl.getHost() + ":" + pageUrl.getPort() + "/" + link;
					} else {
						String path = file.substring(0, file.lastIndexOf('/') + 1);
						link = "http://" + pageUrl.getHost() + ":" + pageUrl.getPort() + path + link;
					}
				}
			}

			int index = link.indexOf('#');
			if (index != -1) {
				link = link.substring(0, index);
			}

			link = removeWwwFromUrl(link);

			URL verifiedLink = verifyUrl(link);
			if (verifiedLink == null) {
				continue;
			}
			/*
			 * If qualified host, excluding those out condition of the URL
			 * 如果限定主机,排除那些不合条件的URL
			 */
			if (limitHost && !pageUrl.getHost().toLowerCase().equals(verifiedLink.getHost().toLowerCase())) {
				continue;
			}
			// jump over those already processing link.跳过那些已经处理的链接.
			if (crawledList.contains(link)) {
				continue;
			}
			linkList.add(link);
		}
		return (linkList);
	}

	// Download the content of the Web page search, judgment in the page does
	// not specify a search string 搜索下载Web页面的内容,判断在该页面内有没有指定的搜索字符串
	private boolean searchStringMatches(String pageContents, String searchString, boolean caseSensitive) {
		String searchContents = pageContents;
		if (!caseSensitive) {// not case sensitive 如果不区分大小写
			searchContents = pageContents.toLowerCase();
		}

		Pattern p = Pattern.compile("[\\s]+");
		String[] terms = p.split(searchString);
		for (int i = 0; i < terms.length; i++) {
			if (caseSensitive) {
				if (searchContents.indexOf(terms[i]) == -1) {
					return false;
				}
			} else {
				if (searchContents.indexOf(terms[i].toLowerCase()) == -1) {
					return false;
				}
			}
		}

		return true;
	}

	// execute search operation 执行实际的搜索操作
	public ArrayList<String> crawl(String startUrl, int maxUrls, String searchString, boolean limithost, boolean caseSensitive) {

		System.out.println("searchString=" + searchString);
		HashSet<String> crawledList = new HashSet<String>();
		LinkedHashSet<String> toCrawlList = new LinkedHashSet<String>();

		if (maxUrls < 1) {
			errorList.add("Invalid Max URLs value.");
			System.out.println("Invalid Max URLs value.");
		}

		if (searchString.length() < 1) {
			errorList.add("Missing Search String.");
			System.out.println("Missing search String");
		}

		if (errorList.size() > 0) {
			System.out.println("err!!!");
			return errorList;
		}

		// remove www from URL 从开始URL中移出www
		startUrl = removeWwwFromUrl(startUrl);

		toCrawlList.add(startUrl);
		while (toCrawlList.size() > 0) {

			if (maxUrls != -1) {
				if (crawledList.size() == maxUrls) {
					break;
				}
			}

			// Get URL at bottom of the list.
			String url = toCrawlList.iterator().next();

			// Remove URL from the to crawl list.
			toCrawlList.remove(url);

			// Convert string url to URL object.
			URL verifiedUrl = verifyUrl(url);

			// Skip URL if robots are not allowed to access it.
			if (!isRobotAllowed(verifiedUrl)) {
				continue;
			}

			// add deal with URL to crawledList 增加已处理的URL到crawledList
			crawledList.add(url);
			String pageContents = downloadPage(verifiedUrl, "gb2312");

			if (pageContents != null && pageContents.length() > 0) {
				// 从页面中获取有效的链接
				ArrayList<String> links = retrieveLinks(verifiedUrl, pageContents, crawledList, limitHost);
				toCrawlList.addAll(links);
				if (searchStringMatches(pageContents, searchString, caseSensitive)) {
					resultList.add(url);
					System.out.println(url);
				}
			}
		}
		return resultList;
	}

	public String downloadPage(URL pageUrl) {
		try {
			HttpURLConnection conn = (HttpURLConnection) pageUrl.openConnection();
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("User-agent", "Mozilla/5.0 Chrome/18.0.1025.166  Safari/535.19");
			conn.connect();

			BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

			// Read page into buffer.
			String line;
			StringBuffer pageBuffer = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				pageBuffer.append(line);
			}
			reader.close();
			return pageBuffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public String downloadPage(URL pageUrl, String codingPattern) {
		try {
			HttpURLConnection conn = (HttpURLConnection) pageUrl.openConnection();
			conn.setDoOutput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("GET");
			conn.setRequestProperty("User-agent", "Mozilla/5.0 (Linux; Android 4.2.1; Nexus 7 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166  Safari/535.19");
			conn.connect();

			// Open connection to URL for reading.
			BufferedReader reader = new BufferedReader(new InputStreamReader(pageUrl.openStream(), codingPattern));

			// Read page into buffer.
			String line = "";
			StringBuffer pageBuffer = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				pageBuffer.append(line);
			}
			reader.close();
			return pageBuffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}

 

 

分享到:
评论

相关推荐

    C++网络爬虫项目

    WEBCRAWLER 网络爬虫实训项目 1 WEBCRAWLER 网 络 爬 虫 实 训 项 目 文档版本: 1.0.0.1 编写单位: 达内IT培训集团 C++教学研发部 编写人员: 闵卫 定稿日期: 2015年11月20日 星期五WEBCRAWLER 网络爬虫实训项目 ...

    分享一个简单的4399游戏名爬虫程序

    自己实现的一个简单的爬虫流程实现,基本功能完善,爬取简单可见的数据,首页面访问,数据过滤,json格式保存

    python网络爬虫-入门基础学习.zip

    网络爬虫要做的,简单来说,就是实现浏览器的功能。通过指定 url ,直接返回给用户所需 要的数据, 而不需要一步步人工去操纵浏览器获取。 1.通用爬虫 VS 聚焦爬虫 1.通用爬虫:搜索引擎使用的爬虫系统 实施 ...

    python网络爬虫-入门基础学习.docx

    网络爬虫要做的,简单来说,就是实现浏览器的功能。通过指定 url ,直接返回给用户所需 要的数据, 而不需要一步步人工去操纵浏览器获取。 1.通用爬虫 VS 聚焦爬虫 1.通用爬虫:搜索引擎使用的爬虫系统 实施 ...

    Python爬虫开发与项目实战-基础爬虫爬取百度百科词条标题-编程项目案例解析实例详解课程教程.pdf

    本章讲解第一个实战项目:基础爬虫。为什么叫基础爬虫呢?首先这个爬虫项目功能简单,仅功能实现,未涉及优化和稳健性的考虑...本次实战项目的需求是爬取100个百度百科网络爬虫词条以及相关词条的标题、摘要和链接等信息。

    Python入门网络爬虫之精华版

    网络爬虫要做的,简单来说,就是实现浏览器的功能。通过指定url,直接返回给用户所需要的数据,而不需要一步步人工去操纵浏览器获取。 抓取 这一步,你要明确要得到的内容是什么?是HTML源码,还是Json格式的字符串...

    网络爬虫调研报告.doc

    网络爬虫调研报告 基本原理 Spider概述 Spider即网络爬虫 ,其定义有广义和狭义之分。狭义上指遵循标准的 http协议利用超链接和 Web文档检索的方法遍历万维网信息空间的软件程序 ;而广义的定义则是所有能遵循 http...

    网络爬虫调研报告(1).doc

    体顶端 网络爬虫调研报告 基本原理 Spider概述 Spider即网络爬虫 ,其定义有广义和狭义之分。狭义上指遵循标准的 http协议利用超链接和 Web文档检索的方法遍历万维网信息空间的软件程序 ;而广义的定义则是所有能遵循 ...

    网络爬虫调研报告(2).doc

    窗体顶端 网络爬虫调研报告 基本原理 Spider概述 Spider即网络爬虫 ,其定义有广义和狭义之分。狭义上指遵循标准的 http协议利用超链接和 Web文档检索的方法遍历万维网信息空间的软件程序 ;而广义的定义则是所有能...

    python爬虫基础知识.docx

    随着互联网的快速发展,大数据时代已经来临。而在获取海量的数据中,网络爬虫...Python作为一门简单易学且功能强大的编程语言,被广泛应用于网络爬虫的开发。本文将介绍Python爬虫的基础知识,并通过实例来详细说明。

    面向零基础初学者简明易懂的 Python3 入门基础课程。在linux+vim生产力环境下,从浅入深,从简单程序学到网络爬虫

    按部就班地学习:建议从基础的Python爬虫开发开始,逐步深入到实际应用中。通过实践,逐步掌握Python爬虫开发的各项技能。 参考项目文件和笔记:项目文件和笔记提供了丰富的背景信息和开发经验。在学习的过程中,...

    网络爬虫系统项目开发实践报告

    网络爬虫项目的实现是基于Java、HTML、MySQL的命令与功能,集成了多种处理方式,锻炼了我们的项目处理能力。 在项目中,我们学习了Java基础,集合框架,MySQL和网页技术。在集合框架中主要学习了List集合、Set集合和...

    简单易用的Python爬虫框架

    教程详尽:配套的Python爬虫教程,从基础到进阶,让您逐步掌握爬虫的核心技术。 合法合规:严格遵守法律法规和网站使用协议,确保采集行为合法,尊重网站权益。 实战项目:结合实际案例,让您在实践中掌握Python爬虫...

    Python基础与应用(Python,数据分析和网络爬虫)

    本科不是简单地介绍Python语法,而是通过案例,有针对性地讲解Python最经典、最核心的功能。 2.Python网络爬虫 人工智能离不开大数据,而数据从何而来呢?没错,使用Python网络爬虫,就可以从浩瀚的互联网中获取海量...

    webcrawler:一个简单的Java实现的网络爬虫,支持自动登录

    第一个网络爬虫介绍Webcrawler 是一个简单的网络爬虫。 它实现了自动登录和内容获取的基本功能。 Webcrawler 将首先尝试使用提供的用户名和密码登录 。 如果登录失败,程序将被终止。 登录后,爬虫将开始获取它可以...

    python爬虫仓库,包括一些学习笔记,例如基础、简单的画图词云数据分析。主要还是爬虫.zip

    爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL...

    Python爬虫案例.md

    《Python网络爬虫入门实战》(崔庆才著):这本书从基础开始介绍了Python爬虫的原理和常用库的使用,通过实战项目帮助你快速入门。 网络教程:有很多免费的在线教程可以帮助你学习Python爬虫,比如Python官方文档中...

    一个简单的python爬虫,原生python+BeautifulSoup.zip

    教程详尽:配套的Python爬虫教程,从基础到进阶,让您逐步掌握爬虫的核心技术。 合法合规:严格遵守法律法规和网站使用协议,确保采集行为合法,尊重网站权益。 实战项目:结合实际案例,让您在实践中掌握Python爬虫...

    Python构建网页爬虫原理分析

    python实现简单爬虫功能的示例 python爬虫实战之最简单的网页爬虫教程 网络爬虫是当今最常用的系统之一。最流行的例子是 Google 使用爬虫从所有网站收集信息。除了搜索引擎之外,新闻网站还需要爬虫来聚合数据源。...

    简单但绝不简陋的 Python3 爬虫项目.zip

    爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫从一个或多个初始URL开始,递归或迭代地发现新的URL,构建一个URL队列。这些URL...

Global site tag (gtag.js) - Google Analytics