陆陆续续做了有一个月,期间因为各种技术问题被多次暂停,最关键的一次主要是因为存储容器使用的普通二叉树,在节点权重相同的情况下导致树高增高,在进行遍历的时候效率大大降低,甚至在使用递归的时候导致栈内存溢出。后来取消递归遍历算法,把普通的二叉排序树升级为平衡二叉树这才解决这些问题。着这个过程中把栈、队列、链表、HashMap、HashTable各种数据结构都重新学习了一遍,使用红黑二叉树实现的TreeMap暂时还没有看,后期需要把TreeMap的实现源码学习一下。

为了把项目做成可扩展性的,方便后期进行升级,又把以前看过的设计模式重新学习了一下,收获不小,对编程思想以及原则理解更进一步。以前看了多次也没有分清楚的简单工厂模式、工厂方法模式和抽象工厂模式这次也搞清楚了。站在系统结构的高度去考虑系统设计还是比较有意思的。

下面就简单介绍一下网络爬虫的实现。

如果把爬虫当做一个系统来进行设计,里面涉及的技术是非常多的,包括:链接解析、链接去重、页面内容去重(不同的URL,但页面内容一样)、页面下载技术、域名高速解析技术……这里的每一项都能够扩展成一个大的主题,甚至可以把这些功能单独列出来做成一个小的项目,进行分布式部署。初期计划把这个爬虫的主要模块做出来留出可扩展接口,后期慢慢一步一步进行各个模块的功能完善,尽量把它做成一个功能比较完善的大型系统。项目已经上传到GitHub中,对爬虫有兴趣的朋友可以扩展一下。https://github.com/PerkinsZhu/WebSprider

系统的结构比较简单,可以看一下类图:

具体讲解一下各个类的作用:

页面实体:PageEntity,代表一个URL。主要有title、URL、weight三个属性,用户可继承继续扩展新的属性。实体必须实现Comparable接口,实现public int compareTo(PageEntity node)方法,在进行存储的时候会根据此方法获取两个节点的比较结果进行存储。

  1. package com.zpj.entity;
  2. /**
  3. * @author PerKins Zhu
  4. * @date:2016年9月2日 下午8:43:26
  5. * @version :1.1
  6. *
  7. */
  8.  
  9. public class PageEntity implements Comparable<PageEntity> {
  10.  
  11. private String title;
  12. private String url;
  13. private float weight;
  14. private int PRIME = 1000000000;
  15.  
  16. public PageEntity(String title, String url, float weight) {
  17. super();
  18. this.title = title;
  19. this.url = url;
  20. this.weight = weight;
  21. }
  22.  
  23. public String getTitle() {
  24. return title;
  25. }
  26.  
  27. public void setTitle(String title) {
  28. this.title = title;
  29. }
  30.  
  31. public String getUrl() {
  32. return url;
  33. }
  34.  
  35. public void setUrl(String url) {
  36. this.url = url;
  37. }
  38.  
  39. public float getWeight() {
  40. return weight;
  41. }
  42.  
  43. public void setWeight(float weight) {
  44. this.weight = weight;
  45. }
  46.  
  47. /**
  48. * 比较优先级: weight > title > url
  49. */
  50. @Override
  51. public int compareTo(PageEntity node) {
  52. if (this.weight == node.weight) {
  53. if (this.title.equals(node.title)) {
  54. if (this.url.equals(node.url)) {
  55. return 0;
  56. } else {
  57. return this.url.compareTo(node.url);
  58. }
  59. } else {
  60. return this.title.compareTo(node.title);
  61. }
  62. } else {
  63. return this.weight > node.weight ? 1 : -1;
  64. }
  65. }
  66.  
  67. //覆写hashCode
  68. @Override
  69. public int hashCode() {
  70. //如果调用父类的hashCode,则每个对象的hashcode都不相同,这里通过url计算hashcode,相同url的hashcode是相同的
  71. int hash, i;
  72. for (hash = this.url.length(), i = 0; i < this.url.length(); ++i)
  73. hash = (hash << 4) ^ (hash >> 28) ^ this.url.charAt(i);
  74. if (hash < 0) {
  75. hash = -hash;
  76. }
  77. return (hash % PRIME);
  78. }
  79.  
  80. }

节点存储容器:PageCollection。用来存储实体对象,在程序中主要用来存储待访问节点PageEntity和访问之后节点的hashCode。

   这里主要使用的是平衡二叉树,不是太了解的话可以看一下:数据结构—平衡二叉树,里面有详细的实现讲解

主要方法有三个对外公开:public Node<T> insert(T data);插入节点

              public T getMaxNode();获取下一个权重最大的节点,同时删除该节点。

              public T get(T data) ;查找指定节点

              public void inorderTraverse();中序遍历多有节点

              public Node<T> remove(T data) ;删除指定节点。

  1. package com.zpj.collection;
  2.  
  3. /**
  4. * @author PerKins Zhu
  5. * @date:2016年9月2日 下午9:03:35
  6. * @version :1.1
  7. *
  8. */
  9.  
  10. public class PageCollection<T extends Comparable<T>> {
  11.  
  12. private Node<T> root;
  13.  
  14. private static class Node<T> {
  15. Node<T> left;
  16. Node<T> right;
  17. T data;
  18. int height;
  19.  
  20. public Node(Node<T> left, Node<T> right, T data) {
  21. this.left = left;
  22. this.right = right;
  23. this.data = data;
  24. this.height = 0;
  25. }
  26. }
  27.  
  28. /**
  29. * 如果树中已经存在该节点则不进行插入,如果没有该节点则进行插入 判断是否存在该节点的方法是compareTo(T node) == 0。
  30. *
  31. * @param data
  32. * @return
  33. */
  34. public Node<T> insert(T data) {
  35. return root = insert(data, root);
  36. }
  37.  
  38. private Node<T> insert(T data, Node<T> node) {
  39. if (node == null)
  40. return new Node<T>(null, null, data);
  41. int compareResult = data.compareTo(node.data);
  42. if (compareResult > 0) {
  43. node.right = insert(data, node.right);
  44. if (getHeight(node.right) - getHeight(node.left) == 2) {
  45. int compareResult02 = data.compareTo(node.right.data);
  46. if (compareResult02 > 0)
  47. node = rotateSingleLeft(node);
  48. else
  49. node = rotateDoubleLeft(node);
  50. }
  51. } else if (compareResult < 0) {
  52. node.left = insert(data, node.left);
  53. if (getHeight(node.left) - getHeight(node.right) == 2) {
  54. int intcompareResult02 = data.compareTo(node.left.data);
  55. if (intcompareResult02 < 0)
  56. node = rotateSingleRight(node);
  57. else
  58. node = rotateDoubleRight(node);
  59. }
  60. }
  61. node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
  62. return node;
  63. }
  64.  
  65. private Node<T> rotateSingleLeft(Node<T> node) {
  66. Node<T> rightNode = node.right;
  67. node.right = rightNode.left;
  68. rightNode.left = node;
  69. node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
  70. rightNode.height = Math.max(node.height, getHeight(rightNode.right)) + 1;
  71. return rightNode;
  72. }
  73.  
  74. private Node<T> rotateSingleRight(Node<T> node) {
  75. Node<T> leftNode = node.left;
  76. node.left = leftNode.right;
  77. leftNode.right = node;
  78. node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
  79. leftNode.height = Math.max(getHeight(leftNode.left), node.height) + 1;
  80. return leftNode;
  81. }
  82.  
  83. private Node<T> rotateDoubleLeft(Node<T> node) {
  84. node.right = rotateSingleRight(node.right);
  85. node = rotateSingleLeft(node);
  86. return node;
  87. }
  88.  
  89. private Node<T> rotateDoubleRight(Node<T> node) {
  90. node.left = rotateSingleLeft(node.left);
  91. node = rotateSingleRight(node);
  92. return node;
  93. }
  94.  
  95. private int getHeight(Node<T> node) {
  96. return node == null ? -1 : node.height;
  97. }
  98.  
  99. public Node<T> remove(T data) {
  100. return root = remove(data, root);
  101. }
  102.  
  103. private Node<T> remove(T data, Node<T> node) {
  104. if (node == null) {
  105. return null;
  106. }
  107. int compareResult = data.compareTo(node.data);
  108. if (compareResult == 0) {
  109. if (node.left != null && node.right != null) {
  110. int balance = getHeight(node.left) - getHeight(node.right);
  111. Node<T> temp = node;
  112. if (balance == -1) {
  113. exChangeRightData(node, node.right);
  114. } else {
  115. exChangeLeftData(node, node.left);
  116. }
  117. temp.height = Math.max(getHeight(temp.left), getHeight(temp.right)) + 1;
  118. return temp;
  119. } else {
  120. return node.left != null ? node.left : node.right;
  121. }
  122. } else if (compareResult > 0) {
  123. node.right = remove(data, node.right);
  124. node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
  125. if (getHeight(node.left) - getHeight(node.right) == 2) {
  126. Node<T> leftSon = node.left;
  127. if (leftSon.left.height > leftSon.right.height) {
  128. node = rotateSingleRight(node);
  129. } else {
  130. node = rotateDoubleRight(node);
  131. }
  132. }
  133. return node;
  134. } else if (compareResult < 0) {
  135. node.left = remove(data, node.left);
  136. node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
  137. if (getHeight(node.left) - getHeight(node.right) == 2) {
  138. Node<T> rightSon = node.right;
  139. if (rightSon.right.height > rightSon.left.height) {
  140. node = rotateSingleLeft(node);
  141. } else {
  142. node = rotateDoubleLeft(node);
  143. }
  144. }
  145. return node;
  146. }
  147. return null;
  148. }
  149.  
  150. private Node<T> exChangeLeftData(Node<T> node, Node<T> right) {
  151. if (right.right != null) {
  152. right.right = exChangeLeftData(node, right.right);
  153. } else {
  154. node.data = right.data;
  155. return right.left;
  156. }
  157. right.height = Math.max(getHeight(right.left), getHeight(right.right)) + 1;
  158. int isbanlance = getHeight(right.left) - getHeight(right.right);
  159. if (isbanlance == 2) {
  160. Node<T> leftSon = node.left;
  161. if (leftSon.left.height > leftSon.right.height) {
  162. return node = rotateSingleRight(node);
  163. } else {
  164. return node = rotateDoubleRight(node);
  165. }
  166. }
  167. return right;
  168. }
  169.  
  170. private Node<T> exChangeRightData(Node<T> node, Node<T> left) {
  171. if (left.left != null) {
  172. left.left = exChangeRightData(node, left.left);
  173. } else {
  174. node.data = left.data;
  175. return left.right;
  176. }
  177. left.height = Math.max(getHeight(left.left), getHeight(left.right)) + 1;
  178. int isbanlance = getHeight(left.left) - getHeight(left.right);
  179. if (isbanlance == -2) {
  180. Node<T> rightSon = node.right;
  181. if (rightSon.right.height > rightSon.left.height) {
  182. return node = rotateSingleLeft(node);
  183. } else {
  184. return node = rotateDoubleLeft(node);
  185. }
  186. }
  187. return left;
  188. }
  189.  
  190. public void inorderTraverse() {
  191. inorderTraverseData(root);
  192. }
  193.  
  194. private void inorderTraverseData(Node<T> node) {
  195. if (node.left != null) {
  196. inorderTraverseData(node.left);
  197. }
  198. System.out.print(node.data + "、");
  199. if (node.right != null) {
  200. inorderTraverseData(node.right);
  201. }
  202. }
  203.  
  204. public boolean isEmpty() {
  205. return root == null;
  206. }
  207.  
  208. // 取出最大权重的节点返回 ,同时删除该节点
  209. public T getMaxNode() {
  210. if (root != null)
  211. root = getMaxNode(root);
  212. else
  213. return null;
  214. return maxNode.data;
  215. }
  216.  
  217. private Node<T> maxNode;
  218.  
  219. private Node<T> getMaxNode(Node<T> node) {
  220. if (node.right == null) {
  221. maxNode = node;
  222. return node.left;
  223. }
  224. node.right = getMaxNode(node.right);
  225. node.height = Math.max(getHeight(node.left), getHeight(node.right)) + 1;
  226. if (getHeight(node.left) - getHeight(node.right) == 2) {
  227. Node<T> leftSon = node.left;
  228. if (isDoubleRotate(leftSon.left, leftSon.right)) {
  229. node = rotateDoubleRight(node);
  230. } else {
  231. node = rotateSingleRight(node);
  232. }
  233. }
  234. return node;
  235. }
  236.  
  237. // 根据节点的树高判断是否需要进行两次旋转 node01是外部节点,node02是内部节点(前提是该节点的祖父节点需要进行旋转)
  238. private boolean isDoubleRotate(Node<T> node01, Node<T> node02) {
  239. // 内部节点不存在,不需要进行两次旋转
  240. if (node02 == null)
  241. return false;
  242. // 外部节点等于null,则内部节点树高必为2,进行两侧旋转
  243. // 外部节点树高小于内部节点树高则必定要进行两次旋转
  244. if (node01 == null || node01.height < node02.height)
  245. return true;
  246. return false;
  247. }
  248.  
  249. /**
  250. * 查找指定节点
  251. * @param data
  252. * @return
  253. */
  254. public T get(T data) {
  255. if (root == null)
  256. return null;
  257. return get(data, root);
  258. }
  259.  
  260. private T get(T data, Node<T> node) {
  261. if (node == null)
  262. return null;
  263. int temp = data.compareTo(node.data);
  264. if (temp == 0) {
  265. return node.data;
  266. } else if (temp > 0) {
  267. return get(data, node.right);
  268. } else if (temp < 0) {
  269. return get(data, node.left);
  270. }
  271. return null;
  272. }
  273.  
  274. }

爬虫核心类:WebSprider,该类实现了Runnable,可进行多线程爬取。

该类中分别用PageCollection<PageEntity> collection 和PageCollection<Integer> visitedCollection来存储待爬取节点和已爬取节点,其中visitedCollection容器存储的是已爬取节点的hashCode,在pageEntity中覆写了hashCode()方法,计算节点hashCode。

在使用的时候客户端需要继承该类实现一个子类,然后实现public abstract Object dealPageEntity(PageEntity entity);抽象方法,在该方法中处理爬取的节点,可以进行输出、存储等操作。WebSprider依赖于HtmlParser。

  1. package com.zpj.sprider;
  2.  
  3. import java.util.List;
  4.  
  5. import com.zpj.collection.PageCollection;
  6. import com.zpj.entity.PageEntity;
  7. import com.zpj.parser.HtmlParser;
  8.  
  9. /**
  10. * @author PerKins Zhu
  11. * @date:2016年9月2日 下午9:02:39
  12. * @version :1.1
  13. *
  14. */
  15.  
  16. public abstract class WebSprider implements Runnable {
  17. private HtmlParser parser;
  18. // 存储待访问的节点
  19. private PageCollection<PageEntity> collection = new PageCollection<PageEntity>();
  20. // 存储已经访问过的节点
  21. private PageCollection<Integer> visitedCollection = new PageCollection<Integer>();
  22.  
  23. public WebSprider(HtmlParser parser, String seed) {
  24. super();
  25. this.parser = parser;
  26. collection.insert(new PageEntity("", seed, 1));
  27. }
  28.  
  29. @Override
  30. public void run() {
  31. PageEntity entity;
  32. while (!collection.isEmpty()) {
  33. entity = collection.getMaxNode();
  34. dealPageEntity(entity);
  35. addToCollection(parser.parser(entity));
  36. }
  37. }
  38.  
  39. private void addToCollection(List<PageEntity> list) {
  40. for (int i = 0; i < list.size(); i++) {
  41. PageEntity pe = list.get(i);
  42. int hashCode = pe.hashCode();
  43. if (visitedCollection.get(hashCode) == null) {
  44. collection.insert(pe);
  45. visitedCollection.insert(hashCode);
  46. }
  47. }
  48. }
  49.  
  50. /**
  51. * 子类对爬取的数据进行处理,可以对entity进行存储或者输出等操作
  52. * @param entity
  53. * @return
  54. */
  55. public abstract Object dealPageEntity(PageEntity entity);
  56. }

页面解析类:HtmlParser

  该类为抽象类,用户需要实现其子类并实现 public abstract NodeList parserUrl(Parser parser);和 public abstract boolean matchesUrl(String url);两个抽象方法。

    public abstract NodeList parserUrl(Parser parser);用来自定义节点过滤器,返回的NodeList就是过滤出的document节点。

     public abstract boolean matchesUrl(String url);用来校验URL是否是用户想要爬取的URL,可以通过正则表达式实现URL校验,返回true则加入容器,否则放弃该URL。

该类依赖于WeightStrategy,权重策略

  1. package com.zpj.parser;
  2.  
  3. import java.net.HttpURLConnection;
  4. import java.net.URL;
  5. import java.util.ArrayList;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Set;
  10.  
  11. import org.htmlparser.Parser;
  12. import org.htmlparser.util.NodeList;
  13.  
  14. import com.zpj.entity.PageEntity;
  15. import com.zpj.weightStrategy.WeightStrategy;
  16.  
  17. /**
  18. * @author PerKins Zhu
  19. * @date:2016年9月2日 下午8:44:39
  20. * @version :1.1
  21. *
  22. */
  23. public abstract class HtmlParser {
  24. private WeightStrategy weightStrategy;
  25. private List<PageEntity> pageList = new ArrayList<PageEntity>();
  26.  
  27. public HtmlParser(WeightStrategy weightStrategy) {
  28. super();
  29. this.weightStrategy = weightStrategy;
  30. }
  31.  
  32. NodeList list;
  33.  
  34. public List<PageEntity> parser(PageEntity pageEntity) {
  35. try {
  36. String entityUrl = pageEntity.getUrl();
  37. URL getUrl = new URL(entityUrl);
  38. HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
  39. connection.connect();
  40. Parser parser;
  41. parser = new Parser(entityUrl);
  42. // TODO 自动设置编码方式
  43. parser.setEncoding(getCharSet(connection));
  44.  
  45. list = parserUrl(parser);
  46. setDefaultWeight();
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. if (list == null)
  51. return pageList;
  52. for (int i = 0; i < list.size(); i++) {
  53. String url = list.elementAt(i).getText().substring(8);
  54. int lastIndex = url.indexOf("\"");
  55. url = url.substring(0, lastIndex == -1 ? url.length() : lastIndex);
  56. if (matchesUrl(url)) {
  57. String title = list.elementAt(i).toPlainTextString();
  58. float weight = weightStrategy.getWeight(title, url);
  59. if (weight <= 1) {
  60. continue;
  61. }
  62. pageList.add(new PageEntity(title, url, weight));
  63. }
  64. }
  65. return pageList;
  66. }
  67.  
  68. private void setDefaultWeight() {
  69. // 解析出body网页文本内容
  70. String text = "";
  71. // 调用权重策略计算本页面中的所有连接的默认权重,每个页面的默认权重都要重新计算
  72. weightStrategy.setDefaultWeightByContent(text);
  73. }
  74.  
  75. /**
  76. * 子类实现方法,通过过滤器过滤出节点集合
  77. * @param parser
  78. * @return
  79. */
  80. public abstract NodeList parserUrl(Parser parser);
  81.  
  82. /**
  83. * 子类实现方法,过滤进行存储的url
  84. * @param url
  85. * @return
  86. */
  87. public abstract boolean matchesUrl(String url);
  88.  
  89. //获取页面编码方式,默认gb2312
  90. private String getCharSet(HttpURLConnection connection) {
  91. Map<String, List<String>> map = connection.getHeaderFields();
  92. Set<String> keys = map.keySet();
  93. Iterator<String> iterator = keys.iterator();
  94. // 遍历,查找字符编码
  95. String key = null;
  96. String tmp = null;
  97. while (iterator.hasNext()) {
  98. key = iterator.next();
  99. tmp = map.get(key).toString().toLowerCase();
  100. // 获取content-type charset
  101. if (key != null && key.equals("Content-Type")) {
  102. int m = tmp.indexOf("charset=");
  103. if (m != -1) {
  104. String charSet = tmp.substring(m + 8).replace("]", "");
  105. return charSet;
  106. }
  107. }
  108. }
  109. return "gb2312";
  110. }
  111.  
  112. }

节点权重计算:WeightStrategy,该类为抽象类,用户可自定义权重计算策略,主要实现如下两个方法:

  public abstract float countWeight(String title, String url) ;根据title和URL计算出该节点的权重,具体算法由用户自己定义

  public abstract void setDefaultWeightByContent(String content);计算出该页面所有连接的基础权重。

也就是说该页面的节点的权重=基础权重(页面权重)+节点权重。基础权重是由该页面的内容分析计算出来,具体算法由public abstract void setDefaultWeightByContent(String content);方法进行计算,然后在public abstract float countWeight(String title, String url) ;计算出该页面中的某个节点权重,最终权重由两者之和。

  1. package com.zpj.weightStrategy;
  2. /**
  3. * @author PerKins Zhu
  4. * @date:2016年9月2日 下午9:04:37
  5. * @version :1.1
  6. *
  7. */
  8.  
  9. public abstract class WeightStrategy {
  10. protected String keyWord;
  11. protected float defaultWeight = 1;
  12.  
  13. public WeightStrategy(String keyWord) {
  14. this.keyWord = keyWord;
  15. }
  16.  
  17. public float getWeight(String title, String url){
  18. return defaultWeight+countWeight(title,url);
  19. };
  20.  
  21. /**
  22. * 计算连接权重,计算结果为:defaultWeight+该方法返回值
  23. * @param title
  24. * @param url
  25. * @return
  26. */
  27. public abstract float countWeight(String title, String url) ;
  28.  
  29. /**
  30. * 根据网页内容计算该页面中所有连接的默认权重
  31. * @param content
  32. */
  33. public abstract void setDefaultWeightByContent(String content);
  34.  
  35. }

核心代码就以上五个类,其中两个为数据存储容器,剩下的三个分别是爬虫抽象类、权重计算抽象类和页面解析抽象类。用户使用的时候需要实现这三个抽象类的子类并实现抽象方法。下面给出一个使使用示例:

页面解析:HtmlParser01

  1. package com.zpj.test;
  2.  
  3. import java.util.regex.Pattern;
  4.  
  5. import org.htmlparser.Node;
  6. import org.htmlparser.NodeFilter;
  7. import org.htmlparser.Parser;
  8. import org.htmlparser.util.NodeList;
  9. import org.htmlparser.util.ParserException;
  10.  
  11. import com.zpj.parser.HtmlParser;
  12. import com.zpj.weightStrategy.WeightStrategy;
  13.  
  14. /**
  15. * @author PerKins Zhu
  16. * @date:2016年9月2日 下午8:46:39
  17. * @version :1.1
  18. *
  19. */
  20. public class HtmlParser01 extends HtmlParser {
  21.  
  22. public HtmlParser01(WeightStrategy weightStrategy) {
  23. super(weightStrategy);
  24. }
  25.  
  26. @Override
  27. public NodeList parserUrl(Parser parser) {
  28. NodeFilter hrefNodeFilter = new NodeFilter() {
  29. @Override
  30. public boolean accept(Node node) {
  31. if (node.getText().startsWith("a href=")) {
  32. return true;
  33. } else {
  34. return false;
  35. }
  36. }
  37. };
  38. try {
  39. return parser.extractAllNodesThatMatch(hrefNodeFilter);
  40. } catch (ParserException e) {
  41. e.printStackTrace();
  42. }
  43. return null;
  44. }
  45.  
  46. @Override
  47. public boolean matchesUrl(String url) {
  48. Pattern p = Pattern
  49. .compile("(http://|ftp://|https://|www){0,1}[^\u4e00-\u9fa5\\s]*?\\.(com|net|cn|me|tw|fr)[^\u4e00-\u9fa5\\s]*");
  50. return p.matcher(url).matches();
  51. }
  52.  
  53. }

权重计算:WeightStrategy01

  1. package com.zpj.test;
  2.  
  3. import com.zpj.weightStrategy.WeightStrategy;
  4.  
  5. /**
  6. * @author PerKins Zhu
  7. * @date:2016年9月2日 下午8:34:19
  8. * @version :1.1
  9. *
  10. */
  11. public class WeightStrategy01 extends WeightStrategy {
  12.  
  13. public WeightStrategy01(String keyWord) {
  14. super(keyWord);
  15. }
  16.  
  17. public float countWeight(String title, String url) {
  18. int temp = 0;
  19. while (-1 != title.indexOf(keyWord)) {
  20. temp++;
  21. title = title.substring(title.indexOf(keyWord) + keyWord.length());
  22. }
  23. return temp * 2;
  24. }
  25.  
  26. @Override
  27. public void setDefaultWeightByContent(String content) {
  28. // 解析文本内容计算defaultWeight
  29. super.defaultWeight = 1;
  30. }
  31.  
  32. }

爬虫主类:MyWebSprider01

  1. package com.zpj.test;
  2.  
  3. import com.zpj.entity.PageEntity;
  4. import com.zpj.parser.HtmlParser;
  5. import com.zpj.sprider.WebSprider;
  6.  
  7. /**
  8. * @author PerKins Zhu
  9. * @date:2016年9月2日 下午8:54:39
  10. * @version :1.1
  11. *
  12. */
  13. public class MyWebSprider01 extends WebSprider {
  14.  
  15. public MyWebSprider01(HtmlParser parser, String seed) {
  16. super(parser, seed);
  17. }
  18.  
  19. @Override
  20. public Object dealPageEntity(PageEntity entity) {
  21. System.out.println(entity.getTitle() + "---" + entity.getWeight() + "--" + entity.getUrl());
  22. return null;
  23. }
  24.  
  25. }

测试类:RunThread

  1. package com.zpj.test;
  2.  
  3. import com.zpj.parser.HtmlParser;
  4. import com.zpj.sprider.WebSprider;
  5. import com.zpj.weightStrategy.WeightStrategy;
  6.  
  7. /**
  8. * @author PerKins Zhu
  9. * @date:2016年9月2日 下午8:34:26
  10. * @version :1.1
  11. *
  12. */
  13. public class RunThread {
  14.  
  15. public static void main(String[] args) {
  16.  
  17. WeightStrategy weightStrategy = new WeightStrategy01("中国");
  18.  
  19. HtmlParser htmlParser = new HtmlParser01(weightStrategy);
  20.  
  21. WebSprider sprider01 = new MyWebSprider01(htmlParser, "http://news.baidu.com/");
  22.  
  23. Thread thread01 = new Thread(sprider01);
  24.  
  25. thread01.start();
  26.  
  27. }
  28. }

程序中需要进行完善的有:存储容器的存储效率问题、已爬取节点限制问题(数量最多1000000000,实际远远小于这个数字)、URL去重策略、PageEntity的扩展问题、爬取出的节点处理问题等,后面会逐步进行优化,优化之后会提交到https://github.com/PerkinsZhu/WebSprider

   对爬虫有兴趣的朋友如果有什么建议或者程序中有什么错误欢迎留言指出 !

-----------------------------------------------------转载请注明出处!------------------------------------------------------------------------------

网络爬虫(java)的更多相关文章

  1. 网络爬虫Java实现抓取网页内容

    package 抓取网页; import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream; ...

  2. Java 网络爬虫获取页面源代码

    原博文:http://www.cnblogs.com/xudong-bupt/archive/2013/03/20/2971893.html 1.网络爬虫是一个自动提取网页的程序,它为搜索引擎从万维网 ...

  3. Java 网络爬虫获取网页源代码原理及实现

    Java 网络爬虫获取网页源代码原理及实现 1.网络爬虫是一个自动提取网页的程序,它为搜索引擎从万维网上下载网页,是搜索引擎的重要组成.传统爬虫从一个或若干初始网页的URL开始,获得初始网页上的URL ...

  4. iOS—网络实用技术OC篇&网络爬虫-使用java语言抓取网络数据

    网络爬虫-使用java语言抓取网络数据 前提:熟悉java语法(能看懂就行) 准备阶段:从网页中获取html代码 实战阶段:将对应的html代码使用java语言解析出来,最后保存到plist文件 上一 ...

  5. Apache Nutch v2.3 发布,Java实现的网络爬虫

    http://www.oschina.net/news/59287/apache-nutch-2-3 Apache Nutch v2.3已经发布了,建议所有使用2.X系列的用户和开发人员升级到这个版本 ...

  6. 黑马程序员——JAVA基础之正则表达式,网络爬虫

    ------Java培训.Android培训.iOS培训..Net培训.期待与您交流! ------- 正则表达式: 概念:用于操作字符串的符合一定规则的表达式 特点:用于一些特定的符号来表示一些代码 ...

  7. Java开发、网络爬虫、自然语言处理、数据挖掘简介

    一.java开发 (1) 应用开发,即Java SE开发,不属于java的优势所在,所以市场占有率很低,前途也不被看好. (2) web开发,即Java Web开发,主要是基于自有或第三方成熟框架的系 ...

  8. 开源的49款Java 网络爬虫软件

    参考地址 搜索引擎 Nutch Nutch 是一个开源Java 实现的搜索引擎.它提供了我们运行自己的搜索引擎所需的全部工具.包括全文搜索和Web爬虫. Nutch的创始人是Doug Cutting, ...

  9. iOS开发——网络实用技术OC篇&网络爬虫-使用java语言抓取网络数据

    网络爬虫-使用java语言抓取网络数据 前提:熟悉java语法(能看懂就行) 准备阶段:从网页中获取html代码 实战阶段:将对应的html代码使用java语言解析出来,最后保存到plist文件 上一 ...

随机推荐

  1. iOS开发 适配iOS10以及Xcode8

    iOS10的适配以及Xcode8使用上的一些注意点 一.证书管理 用Xcode8打开工程后,比较明显的就是下图了,这个是苹果的新特性,可以帮助我们自动管理证书.建议大家勾选这个Automaticall ...

  2. 过滤emoji表情

    str=str.replace(/\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g, "");

  3. nodejs--模块

    在客户端可以将所有的javascript代码分割成几个JS文件,然后在浏览器中将这些JS文件合并.但是在nodejs中是通过以模块为单位来划分所有功能的.每一个模块为一个JS文件,每一个模块中定义的全 ...

  4. keepalived+nginx配置文件及检查nginx服务的脚本

    脚本一启动的速度要快一些哦,因为脚本二要判断两次以后才启动哎 这两个一般配合keepalived使用 脚本一: #!/bin/bash #author:fansik #description:chec ...

  5. AFN的初步封装(post、GET、有无参数)

    #import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface MyURLPost : NSObjec ...

  6. HDU 5937 Equation

    题意: 有1~9数字各有a1, a2, -, a9个, 有无穷多的+和=. 问只用这些数字, 最多能组成多少个不同的等式x+y=z, 其中x,y,z∈[1,9]. 等式中只要有一个数字不一样 就是不一 ...

  7. openjudge 螺旋加密

    /*======================================================================== 25:螺旋加密 总时间限制: 1000ms 内存限 ...

  8. 一起买beta版本文档报告汇总

    一起买beta版本文档报告汇总 031402401鲍亮 031402402曹鑫杰 031402403常松 031402412林淋 031402418汪培侨 031402426许秋鑫 一.Beta版本冲 ...

  9. [Linux] - Docker移动数据到其它盘的办法

    由于使用yum安装Docker,默认是数据是存放在系统盘/var/lib目录下,需要把它放到其实盘里头.方法可以这样做: 1.在其它盘中新建一个目录,比如我的:/yunpan/docker mkdir ...

  10. day27_面向对象进阶

    飒飒 : . . . . 六.描述符 1 描述符是什么:描述符本质就是一个新式类,在这个新式类中,至少实现了__get__(),__set__(),__delete__()中的一个,这也被称为描述符协 ...