采用maven工程,免着到处找依赖jar包

  1. <project xmlns="http://maven.apache.org/POM/4.0.0"
  2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.zhaowu</groupId>
  6. <artifactId>pachong01</artifactId>
  7. <version>0.0.1-SNAPSHOT</version>
  8. <dependencies>
  9. <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
  10. <dependency>
  11. <groupId>org.apache.httpcomponents</groupId>
  12. <artifactId>httpclient</artifactId>
  13. <version>4.5.3</version>
  14. </dependency>
  15.  
  16. <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
  17. <dependency>
  18. <groupId>org.jsoup</groupId>
  19. <artifactId>jsoup</artifactId>
  20. <version>1.11.2</version>
  21. </dependency>
  22.  
  23. <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
  24. <dependency>
  25. <groupId>commons-io</groupId>
  26. <artifactId>commons-io</artifactId>
  27. <version>2.6</version>
  28. </dependency>
  29.  
  30. <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
  31. <dependency>
  32. <groupId>org.quartz-scheduler</groupId>
  33. <artifactId>quartz</artifactId>
  34. <version>2.3.0</version>
  35. </dependency>
  36.  
  37. <!-- https://mvnrepository.com/artifact/cn.edu.hfut.dmic.webcollector/WebCollector -->
  38. <dependency>
  39. <groupId>cn.edu.hfut.dmic.webcollector</groupId>
  40. <artifactId>WebCollector</artifactId>
  41. <version>2.71</version>
  42. </dependency>
  43.  
  44. <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
  45. <dependency>
  46. <groupId>org.apache.poi</groupId>
  47. <artifactId>poi</artifactId>
  48. <version>3.17</version>
  49. </dependency>
  50.  
  51. <!-- https://mvnrepository.com/artifact/net.sourceforge.htmlunit/htmlunit -->
  52. <dependency>
  53. <groupId>net.sourceforge.htmlunit</groupId>
  54. <artifactId>htmlunit</artifactId>
  55. <version>2.29</version>
  56. </dependency>
  57.  
  58. </dependencies>
  59. </project>

直接上代码RenWu.class:

  1. package com.zhaowu.renwu2;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.InputStreamReader;
  7. import java.net.MalformedURLException;
  8. import java.net.URL;
  9.  
  10. import org.jsoup.Jsoup;
  11. import org.jsoup.nodes.Document;
  12. import org.jsoup.nodes.Element;
  13. import org.jsoup.select.Elements;
  14.  
  15. import com.gargoylesoftware.htmlunit.BrowserVersion;
  16. import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
  17. import com.gargoylesoftware.htmlunit.WebClient;
  18. import com.gargoylesoftware.htmlunit.html.HtmlInput;
  19. import com.gargoylesoftware.htmlunit.html.HtmlPage;
  20.  
  21. public class RenWu {
  22. // 搜索页数
  23. private static int N = 6;
  24. // 搜索关键词
  25. private static String keyWord = "爬虫";
  26. // 第一页搜索结果
  27. private static HtmlPage firstBaiduPage;
  28. // Baidu对应每个搜索结果的第一页第二页第三页等等其中包含“&pn=1”,“&pn=2”,“&pn=3”等等,
  29. // 提取该链接并处理可以获取到一个模板,用于定位某页搜索结果
  30. private static String template = "";
  31.  
  32. public static void main(String[] args) {
  33. goSearch(N, keyWord);
  34. }
  35.  
  36. private static void goSearch(final int n, final String keyWord) {
  37. Thread thread = new Thread(new Runnable() {
  38. public void run() {
  39. // 页数
  40. int x = n;
  41. System.out.println("爬取百度关于关键字“" + keyWord + "”搜索结果的前" + x + "页");
  42. FileUtil.toFile("爬取百度关于关键字“" + keyWord + "”搜索结果的前" + x + "页\n");
  43.  
  44. //1.获取并输出第一页百度查询内容
  45. Elements firstElementsLink = null;
  46. try {
  47. firstElementsLink = getFirstPage(keyWord);
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }
  51. for (Element link : firstElementsLink) {
  52. // 链接url
  53. String linkHref = link.attr("href");
  54. // 链接标题
  55. String linkText = link.text();
  56. if(linkHref.length() > 13 & linkText.length() > 4) {
  57. String content = "链接url: " + linkHref + "\n\t链接标题: " + linkText + "\n";
  58. System.out.println(content);
  59. FileUtil.toFile(content);
  60. }
  61. }
  62.  
  63. //2.读取第二页及之后页面预处理
  64. // 以firstBaiduPage作为参数,定义template,即网页格式。
  65. nextHref(firstBaiduPage);
  66.  
  67. //3.获取百度第一页之后的搜索结果
  68. for(int i = 1; i< x; i++) {
  69. System.out.println("\n---------百度搜索关键字“" + keyWord + "”第" + (i + 1) + "页结果------");
  70. FileUtil.toFile("\n---------百度搜索关键字“" + keyWord + "”第" + (i + 1) + "页结果------" + "\n");
  71. // 根据已知格式修改生成新的一页的链接
  72. String tempURL = template.replaceAll("&pn=1", "&pn=" + i + "");
  73. // 显示该搜索模板
  74. System.out.println("\t该页地址为:" + tempURL);
  75. RenWu renWu = new RenWu();
  76. // 实现摘取网页源码
  77. String htmls = renWu.getPageSource(tempURL, "utf-8");
  78. // 网页信息转换为jsoup可识别的doc模式
  79. Document doc = Jsoup.parse(htmls);
  80. // 摘取该页搜索链接
  81. Elements links = doc.select("a[data-click]");
  82. // 该处同上getFirstPage的相关实现
  83. for (Element link : links) {
  84. // 链接url
  85. String linkHref = link.attr("href");
  86. // 链接标题
  87. String linkText = link.text();
  88. if(linkHref.length() > 13 & linkText.length() > 4) {
  89. String content = "链接url: " + linkHref + "\n\t链接标题: " + linkText + "\n";
  90. System.out.println(content);
  91. FileUtil.toFile(content);
  92. }
  93. }
  94. }
  95. }
  96. });
  97. thread.start();
  98. }
  99.  
  100. public String getPageSource(String pageURL, String encoding) {
  101. // 输入:url链接&编码格式
  102. // 输出:该网页内容
  103. StringBuffer sb = new StringBuffer();
  104. try {
  105. // 构建一URL对象
  106. URL url = new URL(pageURL);
  107. // 使用openStream得到一输入流并由此构造一个BufferedReader对象
  108. InputStream in = url.openStream();
  109. InputStreamReader ir = new InputStreamReader(in);
  110. BufferedReader br = new BufferedReader(ir);
  111. String line;
  112. while((line = br.readLine()) != null) {
  113. sb.append(line);
  114. sb.append("\n");
  115. }
  116. br.close();
  117. } catch (Exception e) {
  118. e.printStackTrace();
  119. }
  120. return sb.toString();
  121. }
  122.  
  123. /*
  124. * 获取百度搜索第一页内容
  125. */
  126. public static Elements getFirstPage(String keyWord) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
  127. //设置浏览器的User-Agent
  128. WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
  129. // HtmlUnit对JavaScript的支持不好,关闭之
  130. webClient.getOptions().setJavaScriptEnabled(false);
  131. // HtmlUnit对CSS的支持不好,关闭之
  132. webClient.getOptions().setCssEnabled(false);
  133. // 百度搜索首页页面
  134. HtmlPage htmlPage = webClient.getPage("http://www.baidu.com/");
  135. // 获取搜索输入框并提交搜索内容(查看源码获取元素名称)
  136. HtmlInput input = htmlPage.getHtmlElementById("kw");
  137. // 将搜索词模拟填进百度输入框(元素ID如上)
  138. input.setValueAttribute(keyWord);
  139. // 获取搜索按钮并点击
  140. HtmlInput btn = htmlPage.getHtmlElementById("su");
  141. // 模拟搜索按钮事件,获取第一页的html内容
  142. firstBaiduPage = btn.click();
  143. // 将获取到的百度搜索的第一页信息输出
  144. // 通过page.asXml()来获取百度首页的源代码,
  145. // 通过page.asTest()来获取页面的文字
  146. String content = firstBaiduPage.asXml().toString();
  147. // 转换为Jsoup识别的doc格式
  148. Document doc = Jsoup.parse(content);
  149. System.out.println("---------百度搜索关键字“" + keyWord + "”第1页结果--------");
  150. FileUtil.toFile("---------百度搜索关键字“" + keyWord + "”第1页结果--------" + "\n");
  151. // 返回包含类似<a......data-click=" "......>等的元素
  152. Elements firstElementsLink = doc.select("a[data-click]");
  153. // 返回此类链接,即第一页的百度搜素链接
  154. return firstElementsLink;
  155. }
  156.  
  157. /*
  158. * 获取下一页地址
  159. */
  160. public static void nextHref(HtmlPage firstBaiduPage) {
  161.  
  162. WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
  163. webClient.getOptions().setJavaScriptEnabled(false);
  164. webClient.getOptions().setCssEnabled(false);
  165. // 获取到百度第一页搜索的底端的页码的html代码
  166. String morelinks = firstBaiduPage.getElementById("page").asXml();
  167. // 转换为Jsoup识别的doc格式
  168. Document doc = Jsoup.parse(morelinks);
  169. // 提取这个html中的包含<a href=""....>的部分
  170. Elements links = doc.select("a[href]");
  171. // 设置只取一次每页链接的模板格式
  172. boolean getTemplate = true;
  173. for (Element e : links) {
  174. // 将提取出来的<a>标签中的链接取出
  175. String linkHref = e.attr("href");
  176. if(getTemplate) {
  177. // 补全模板格式
  178. template = "http://www.baidu.com" + linkHref;
  179. getTemplate = false;
  180. }
  181. }
  182. }
  183. }

导出到本地文件(末尾追加)的封装方发类FileUtil.class:

  1. package com.zhaowu.renwu2;
  2.  
  3. import java.io.File;
  4. import java.io.FileWriter;
  5. import java.io.IOException;
  6.  
  7. public class FileUtil {
  8. public static void toFile (String content) {
  9. File file = null;
  10. FileWriter fw = null;
  11. file = new File("/home/acer/桌面/aaa");
  12. try {
  13. if (!file.exists()) {
  14. file.createNewFile();
  15. }
  16. fw = new FileWriter(file,true);
  17. fw.write(content);//向文件中复制内容
  18. fw.flush();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }finally{
  22. if(fw != null){
  23. try {
  24. fw.close();
  25. } catch (IOException e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }
  30. }
  31. }

爬虫任务二:爬取(用到htmlunit和jsoup)通过百度搜索引擎关键字搜取到的新闻标题和url,并保存在本地文件中(主体借鉴了网上的资料)的更多相关文章

  1. scrapy-redis实现爬虫分布式爬取分析与实现

    本文链接:http://blog.csdn.net/u012150179/article/details/38091411 一 scrapy-redis实现分布式爬取分析 所谓的scrapy-redi ...

  2. 网络爬虫之定向爬虫:爬取当当网2015年图书销售排行榜信息(Crawler)

    做了个爬虫,爬取当当网--2015年图书销售排行榜 TOP500 爬取的基本思想是:通过浏览网页,列出你所想要获取的信息,然后通过浏览网页的源码和检查(这里用的是chrome)来获相关信息的节点,最后 ...

  3. 使用htmlparse爬虫技术爬取电影网页的全部下载链接

    昨天,我们利用webcollector爬虫技术爬取了网易云音乐17万多首歌曲,而且还包括付费的在内,如果时间允许的话,可以获取更多的音乐下来,当然,也有小伙伴留言说这样会降低国人的知识产权保护意识,诚 ...

  4. python 爬虫之爬取大街网(思路)

    由于需要,本人需要对大街网招聘信息进行分析,故写了个爬虫进行爬取.这里我将记录一下,本人爬取大街网的思路. 附:爬取得数据仅供自己分析所用,并未用作其它用途. 附:本篇适合有一定 爬虫基础 crawl ...

  5. Python爬虫之爬取慕课网课程评分

    BS是什么? BeautifulSoup是一个基于标签的文本解析工具.可以根据标签提取想要的内容,很适合处理html和xml这类语言文本.如果你希望了解更多关于BS的介绍和用法,请看Beautiful ...

  6. Java爬虫实践--爬取CSDN网站图片为例

    实现的效果,自动在工程下创建Pictures文件夹,根据网站URL爬取图片,层层获取.在Pictures下以网站的层级URL命名文件夹,用来装该层URL下的图片.同时将文件名,路径,URL插入数据库, ...

  7. [Python爬虫] Selenium爬取新浪微博客户端用户信息、热点话题及评论 (上)

    转载自:http://blog.csdn.net/eastmount/article/details/51231852 一. 文章介绍 源码下载地址:http://download.csdn.net/ ...

  8. python爬虫项目-爬取雪球网金融数据(关注、持续更新)

    (一)python金融数据爬虫项目 爬取目标:雪球网(起始url:https://xueqiu.com/hq#exchange=CN&firstName=1&secondName=1_ ...

  9. python3编写网络爬虫19-app爬取

    一.app爬取 前面都是介绍爬取Web网页的内容,随着移动互联网的发展,越来越多的企业并没有提供Web页面端的服务,而是直接开发了App,更多信息都是通过App展示的 App爬取相比Web端更加容易 ...

随机推荐

  1. python 同时遍历多个变量

    最近在用python的时候,用到遍历多个变量: import sys import math F58=11491939491.7 F=[11429229079.7,11374540753.7,1132 ...

  2. node.js安装与入门使用

    一个基于 Chrome V8 引擎的 JavaScript 运行环境. Node.js 的包管理器 npm,是全球最大的开源库生态系统. 提供事件驱动和非阻塞I/O API,可优化应用程序的吞吐量和规 ...

  3. 嵌入式驱动开发之dsp 算法优化vlib emcv---算法优化

    http://www.opencv.org.cn/forum.php?mod=forumdisplay&fid=9

  4. 一个stream!=NULL 的问题 fclose.c 47

    运行一段时间会出现如下错误提示:Debug Assertion Failed!Program:...File:fseek.cline:100Expression: (stream!=NULL) 点Re ...

  5. php获取文件后缀的9种方法

    获取文件后缀的9种方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 3 ...

  6. MathType输入补集符号的步骤有哪些

    集合符号在很多的数学领域都会用到,其基本的集合运算可以分为交.并.补这三种.但是一些用户朋友们在编辑文档的时候想输入集合符号这个时候就需要用到数学公式编辑器MathType,但是很多人能够快速地编辑出 ...

  7. 【分享】DevDocs API Documentation

    http://devdocs.io/ 这是一份综合性的在线API列表,很全,方便查找.

  8. React资料

    基于ReactNative开发的APPhttp://reactnative.cn/cases.htmlhttp://www.cnblogs.com/qiangxia/p/5584622.html F8 ...

  9. const在指针中的用法

    一.指向const对象的指针---对象不能修改 方式1 int value1 = 3; const int *p1 = &value1; *p1 = 5; //错误,不能修改const指向对象 ...

  10. 怎样開始学习ADF和Jdeveroper 11g

    先给一些资料能够帮助刚開始学习的人開始学习ADF和Jdeveloper11g 1.首先毫无疑问,你要懂java语言. 能够看看Thinking In Java, 或者原来sun的网上的一些文档Sun' ...