转载请注明出处:http://blog.csdn.NET/lmj623565791/article/details/23272657

今天公司有个需求,需要做一些指定网站查询后的数据的抓取,于是花了点时间写了个demo供演示使用。

思想很简单:就是通过Java访问的链接,然后拿到html字符串,然后就是解析链接等需要的数据。

技术上使用Jsoup方便页面的解析,当然Jsoup很方便,也很简单,一行代码就能知道怎么用了:

  1. Document doc = Jsoup.connect("http://www.oschina.net/")
  2. .data("query", "Java")   // 请求参数
  3. .userAgent("I ’ m jsoup") // 设置 User-Agent
  4. .cookie("auth", "token") // 设置 cookie
  5. .timeout(3000)           // 设置连接超时时间
  6. .post();                 // 使用 POST 方法访问 URL

下面介绍整个实现过程:

1、分析需要解析的页面:

网址:http://www1.sxcredit.gov.cn/public/infocomquery.do?method=publicIndexQuery

页面:

先在这个页面上做一次查询:观察下请求的url,参数,method等。

这里我们使用chrome内置的开发者工具(快捷键F12),下面是查询的结果:

我们可以看到url,method,以及参数。知道了如何或者查询的URL,下面就开始代码了,为了重用与扩展,我定义了几个类:

1、Rule.java用于指定查询url,method,params等

  1. package com.zhy.spider.rule;
  2. /**
  3. * 规则类
  4. *
  5. * @author zhy
  6. *
  7. */
  8. public class Rule
  9. {
  10. /**
  11. * 链接
  12. */
  13. private String url;
  14. /**
  15. * 参数集合
  16. */
  17. private String[] params;
  18. /**
  19. * 参数对应的值
  20. */
  21. private String[] values;
  22. /**
  23. * 对返回的HTML,第一次过滤所用的标签,请先设置type
  24. */
  25. private String resultTagName;
  26. /**
  27. * CLASS / ID / SELECTION
  28. * 设置resultTagName的类型,默认为ID
  29. */
  30. private int type = ID ;
  31. /**
  32. *GET / POST
  33. * 请求的类型,默认GET
  34. */
  35. private int requestMoethod = GET ;
  36. public final static int GET = 0 ;
  37. public final static int POST = 1 ;
  38. public final static int CLASS = 0;
  39. public final static int ID = 1;
  40. public final static int SELECTION = 2;
  41. public Rule()
  42. {
  43. }
  44. public Rule(String url, String[] params, String[] values,
  45. String resultTagName, int type, int requestMoethod)
  46. {
  47. super();
  48. this.url = url;
  49. this.params = params;
  50. this.values = values;
  51. this.resultTagName = resultTagName;
  52. this.type = type;
  53. this.requestMoethod = requestMoethod;
  54. }
  55. public String getUrl()
  56. {
  57. return url;
  58. }
  59. public void setUrl(String url)
  60. {
  61. this.url = url;
  62. }
  63. public String[] getParams()
  64. {
  65. return params;
  66. }
  67. public void setParams(String[] params)
  68. {
  69. this.params = params;
  70. }
  71. public String[] getValues()
  72. {
  73. return values;
  74. }
  75. public void setValues(String[] values)
  76. {
  77. this.values = values;
  78. }
  79. public String getResultTagName()
  80. {
  81. return resultTagName;
  82. }
  83. public void setResultTagName(String resultTagName)
  84. {
  85. this.resultTagName = resultTagName;
  86. }
  87. public int getType()
  88. {
  89. return type;
  90. }
  91. public void setType(int type)
  92. {
  93. this.type = type;
  94. }
  95. public int getRequestMoethod()
  96. {
  97. return requestMoethod;
  98. }
  99. public void setRequestMoethod(int requestMoethod)
  100. {
  101. this.requestMoethod = requestMoethod;
  102. }
  103. }

简单说一下:这个规则类定义了我们查询过程中需要的所有信息,方便我们的扩展,以及代码的重用,我们不可能针对每个需要抓取的网站写一套代码。

2、需要的数据对象,目前只需要链接,LinkTypeData.java

  1. package com.zhy.spider.bean;
  2. public class LinkTypeData
  3. {
  4. private int id;
  5. /**
  6. * 链接的地址
  7. */
  8. private String linkHref;
  9. /**
  10. * 链接的标题
  11. */
  12. private String linkText;
  13. /**
  14. * 摘要
  15. */
  16. private String summary;
  17. /**
  18. * 内容
  19. */
  20. private String content;
  21. public int getId()
  22. {
  23. return id;
  24. }
  25. public void setId(int id)
  26. {
  27. this.id = id;
  28. }
  29. public String getLinkHref()
  30. {
  31. return linkHref;
  32. }
  33. public void setLinkHref(String linkHref)
  34. {
  35. this.linkHref = linkHref;
  36. }
  37. public String getLinkText()
  38. {
  39. return linkText;
  40. }
  41. public void setLinkText(String linkText)
  42. {
  43. this.linkText = linkText;
  44. }
  45. public String getSummary()
  46. {
  47. return summary;
  48. }
  49. public void setSummary(String summary)
  50. {
  51. this.summary = summary;
  52. }
  53. public String getContent()
  54. {
  55. return content;
  56. }
  57. public void setContent(String content)
  58. {
  59. this.content = content;
  60. }
  61. }

3、核心的查询类:ExtractService.java

  1. package com.zhy.spider.core;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Map;
  6. import javax.swing.plaf.TextUI;
  7. import org.jsoup.Connection;
  8. import org.jsoup.Jsoup;
  9. import org.jsoup.nodes.Document;
  10. import org.jsoup.nodes.Element;
  11. import org.jsoup.select.Elements;
  12. import com.zhy.spider.bean.LinkTypeData;
  13. import com.zhy.spider.rule.Rule;
  14. import com.zhy.spider.rule.RuleException;
  15. import com.zhy.spider.util.TextUtil;
  16. /**
  17. *
  18. * @author zhy
  19. *
  20. */
  21. public class ExtractService
  22. {
  23. /**
  24. * @param rule
  25. * @return
  26. */
  27. public static List<LinkTypeData> extract(Rule rule)
  28. {
  29. // 进行对rule的必要校验
  30. validateRule(rule);
  31. List<LinkTypeData> datas = new ArrayList<LinkTypeData>();
  32. LinkTypeData data = null;
  33. try
  34. {
  35. /**
  36. * 解析rule
  37. */
  38. String url = rule.getUrl();
  39. String[] params = rule.getParams();
  40. String[] values = rule.getValues();
  41. String resultTagName = rule.getResultTagName();
  42. int type = rule.getType();
  43. int requestType = rule.getRequestMoethod();
  44. Connection conn = Jsoup.connect(url);
  45. // 设置查询参数
  46. if (params != null)
  47. {
  48. for (int i = 0; i < params.length; i++)
  49. {
  50. conn.data(params[i], values[i]);
  51. }
  52. }
  53. // 设置请求类型
  54. Document doc = null;
  55. switch (requestType)
  56. {
  57. case Rule.GET:
  58. doc = conn.timeout(100000).get();
  59. break;
  60. case Rule.POST:
  61. doc = conn.timeout(100000).post();
  62. break;
  63. }
  64. //处理返回数据
  65. Elements results = new Elements();
  66. switch (type)
  67. {
  68. case Rule.CLASS:
  69. results = doc.getElementsByClass(resultTagName);
  70. break;
  71. case Rule.ID:
  72. Element result = doc.getElementById(resultTagName);
  73. results.add(result);
  74. break;
  75. case Rule.SELECTION:
  76. results = doc.select(resultTagName);
  77. break;
  78. default:
  79. //当resultTagName为空时默认去body标签
  80. if (TextUtil.isEmpty(resultTagName))
  81. {
  82. results = doc.getElementsByTag("body");
  83. }
  84. }
  85. for (Element result : results)
  86. {
  87. Elements links = result.getElementsByTag("a");
  88. for (Element link : links)
  89. {
  90. //必要的筛选
  91. String linkHref = link.attr("href");
  92. String linkText = link.text();
  93. data = new LinkTypeData();
  94. data.setLinkHref(linkHref);
  95. data.setLinkText(linkText);
  96. datas.add(data);
  97. }
  98. }
  99. } catch (IOException e)
  100. {
  101. e.printStackTrace();
  102. }
  103. return datas;
  104. }
  105. /**
  106. * 对传入的参数进行必要的校验
  107. */
  108. private static void validateRule(Rule rule)
  109. {
  110. String url = rule.getUrl();
  111. if (TextUtil.isEmpty(url))
  112. {
  113. throw new RuleException("url不能为空!");
  114. }
  115. if (!url.startsWith("http://"))
  116. {
  117. throw new RuleException("url的格式不正确!");
  118. }
  119. if (rule.getParams() != null && rule.getValues() != null)
  120. {
  121. if (rule.getParams().length != rule.getValues().length)
  122. {
  123. throw new RuleException("参数的键值对个数不匹配!");
  124. }
  125. }
  126. }
  127. }

4、里面用了一个异常类:RuleException.java

  1. package com.zhy.spider.rule;
  2. public class RuleException extends RuntimeException
  3. {
  4. public RuleException()
  5. {
  6. super();
  7. // TODO Auto-generated constructor stub
  8. }
  9. public RuleException(String message, Throwable cause)
  10. {
  11. super(message, cause);
  12. // TODO Auto-generated constructor stub
  13. }
  14. public RuleException(String message)
  15. {
  16. super(message);
  17. // TODO Auto-generated constructor stub
  18. }
  19. public RuleException(Throwable cause)
  20. {
  21. super(cause);
  22. // TODO Auto-generated constructor stub
  23. }
  24. }

5、最后是测试了:这里使用了两个网站进行测试,采用了不同的规则,具体看代码吧

  1. package com.zhy.spider.test;
  2. import java.util.List;
  3. import com.zhy.spider.bean.LinkTypeData;
  4. import com.zhy.spider.core.ExtractService;
  5. import com.zhy.spider.rule.Rule;
  6. public class Test
  7. {
  8. @org.junit.Test
  9. public void getDatasByClass()
  10. {
  11. Rule rule = new Rule(
  12. "http://www1.sxcredit.gov.cn/public/infocomquery.do?method=publicIndexQuery",
  13. new String[] { "query.enterprisename","query.registationnumber" }, new String[] { "兴网","" },
  14. "cont_right", Rule.CLASS, Rule.POST);
  15. List<LinkTypeData> extracts = ExtractService.extract(rule);
  16. printf(extracts);
  17. }
  18. @org.junit.Test
  19. public void getDatasByCssQuery()
  20. {
  21. Rule rule = new Rule("http://www.11315.com/search",
  22. new String[] { "name" }, new String[] { "兴网" },
  23. "div.g-mn div.con-model", Rule.SELECTION, Rule.GET);
  24. List<LinkTypeData> extracts = ExtractService.extract(rule);
  25. printf(extracts);
  26. }
  27. public void printf(List<LinkTypeData> datas)
  28. {
  29. for (LinkTypeData data : datas)
  30. {
  31. System.out.println(data.getLinkText());
  32. System.out.println(data.getLinkHref());
  33. System.out.println("***********************************");
  34. }
  35. }
  36. }

输出结果:

  1. 深圳市网兴科技有限公司
  2. http://14603257.11315.com
  3. ***********************************
  4. 荆州市兴网公路物资有限公司
  5. http://05155980.11315.com
  6. ***********************************
  7. 西安市全兴网吧
  8. #
  9. ***********************************
  10. 子长县新兴网城
  11. #
  12. ***********************************
  13. 陕西同兴网络信息有限责任公司第三分公司
  14. #
  15. ***********************************
  16. 西安高兴网络科技有限公司
  17. #
  18. ***********************************
  19. 陕西同兴网络信息有限责任公司西安分公司
  20. #
  21. ***********************************

最后使用一个Baidu新闻来测试我们的代码:说明我们的代码是通用的。

  1. /**
  2. * 使用百度新闻,只设置url和关键字与返回类型
  3. */
  4. @org.junit.Test
  5. public void getDatasByCssQueryUserBaidu()
  6. {
  7. Rule rule = new Rule("http://news.baidu.com/ns",
  8. new String[] { "word" }, new String[] { "支付宝" },
  9. null, -1, Rule.GET);
  10. List<LinkTypeData> extracts = ExtractService.extract(rule);
  11. printf(extracts);
  12. }

我们只设置了链接、关键字、和请求类型,不设置具体的筛选条件。

结果:有一定的垃圾数据是肯定的,但是需要的数据肯定也抓取出来了。我们可以设置Rule.SECTION,以及筛选条件进一步的限制。

  1. 按时间排序
  2. /ns?word=支付宝&ie=utf-8&bs=支付宝&sr=0&cl=2&rn=20&tn=news&ct=0&clk=sortbytime
  3. ***********************************
  4. x
  5. javascript:void(0)
  6. ***********************************
  7. 支付宝将联合多方共建安全基金 首批投入4000万
  8. http://finance.ifeng.com/a/20140409/12081871_0.shtml
  9. ***********************************
  10. 7条相同新闻
  11. /ns?word=%E6%94%AF%E4%BB%98%E5%AE%9D+cont:2465146414%7C697779368%7C3832159921&same=7&cl=1&tn=news&rn=30&fm=sd
  12. ***********************************
  13. 百度快照
  14. http://cache.baidu.com/c?m=9d78d513d9d437ab4f9e91697d1cc0161d4381132ba7d3020cd0870fd33a541b0120a1ac26510d19879e20345dfe1e4bea876d26605f75a09bbfd91782a6c1352f8a2432721a844a0fd019adc1452fc423875d9dad0ee7cdb168d5f18c&p=c96ec64ad48b2def49bd9b780b64&newp=c4769a4790934ea95ea28e281c4092695912c10e3dd796&user=baidu&fm=sc&query=%D6%A7%B8%B6%B1%A6&qid=a400f3660007a6c5&p1=1
  15. ***********************************
  16. OpenSSL漏洞涉及众多网站 支付宝称暂无数据泄露
  17. http://tech.ifeng.com/internet/detail_2014_04/09/35590390_0.shtml
  18. ***********************************
  19. 26条相同新闻
  20. /ns?word=%E6%94%AF%E4%BB%98%E5%AE%9D+cont:3869124100&same=26&cl=1&tn=news&rn=30&fm=sd
  21. ***********************************
  22. 百度快照
  23. http://cache.baidu.com/c?m=9f65cb4a8c8507ed4fece7631050803743438014678387492ac3933fc239045c1c3aa5ec677e4742ce932b2152f4174bed843670340537b0efca8e57dfb08f29288f2c367117845615a71bb8cb31649b66cf04fdea44a7ecff25e5aac5a0da4323c044757e97f1fb4d7017dd1cf4&p=8b2a970d95df11a05aa4c32013&newp=9e39c64ad4dd50fa40bd9b7c5253d8304503c52251d5ce042acc&user=baidu&fm=sc&query=%D6%A7%B8%B6%B1%A6&qid=a400f3660007a6c5&p1=2
  24. ***********************************
  25. 雅虎日本6月起开始支持支付宝付款
  26. http://www.techweb.com.cn/ucweb/news/id/2025843
  27. ***********************************

如果有什么不足,可以指出;

源码下载,请点击这里

原文博客的链接地址:https://cnblogs.com/qzf/

最新文章

  1. JavaScript的Dom操作
  2. html5 Application Cache 机制以及使用
  3. LOL(英雄联盟)提示不支持虚拟机登录,解决方法
  4. 关于ArcGIS10.0中的栅格计算中的函数
  5. Oracle 10g dataguard broker 配置
  6. DWZ (JUI) 教程 根据ID刷新 dialog
  7. !!流行的php面试题及答案
  8. STL set_difference set_intersection set_union 操作
  9. Java的云打印Lodop
  10. AnimationDrawable 资源
  11. bzoj3293 [Cqoi2011]分金币&amp;&amp;bzoj1045 [HAOI2008]糖果传递
  12. sffs
  13. C++小知识之Vector排序
  14. 【百度地图API】如何激发手机的高分辨率
  15. Swift 使用Extension 场景 浅析
  16. java程序调用存储过程和存储函数
  17. oracle 查询表中数据行(row)上最后的DML时间
  18. 编译模块的Makefile解析
  19. D01-R语言基础学习
  20. ssh免密码登录之ssh-keygen的用法

热门文章

  1. 4.struts2的配置文件优先级
  2. IExpress 制作安装包 注意事项
  3. 定制sudo的密码保持时间以及如何不需要密码
  4. Object-c 创建按钮
  5. unity 加载读取外部XML
  6. 消息 14607,级别 16,状态 1,过程 sp_send_dbmail,第 141 行 profile 名称无效
  7. 每月IT摘录201808--201809
  8. LuoguP1032 字符变换(BFS)
  9. hdoj1075-What Are You Talking About 【map】
  10. C++中纯虚函数