爬虫任务二:爬取(用到htmlunit和jsoup)通过百度搜索引擎关键字搜取到的新闻标题和url,并保存在本地文件中(主体借鉴了网上的资料)
采用maven工程,免着到处找依赖jar包
- <project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.zhaowu</groupId>
- <artifactId>pachong01</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <dependencies>
- <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>4.5.3</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.jsoup/jsoup -->
- <dependency>
- <groupId>org.jsoup</groupId>
- <artifactId>jsoup</artifactId>
- <version>1.11.2</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.6</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.quartz-scheduler/quartz -->
- <dependency>
- <groupId>org.quartz-scheduler</groupId>
- <artifactId>quartz</artifactId>
- <version>2.3.0</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/cn.edu.hfut.dmic.webcollector/WebCollector -->
- <dependency>
- <groupId>cn.edu.hfut.dmic.webcollector</groupId>
- <artifactId>WebCollector</artifactId>
- <version>2.71</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
- <dependency>
- <groupId>org.apache.poi</groupId>
- <artifactId>poi</artifactId>
- <version>3.17</version>
- </dependency>
- <!-- https://mvnrepository.com/artifact/net.sourceforge.htmlunit/htmlunit -->
- <dependency>
- <groupId>net.sourceforge.htmlunit</groupId>
- <artifactId>htmlunit</artifactId>
- <version>2.29</version>
- </dependency>
- </dependencies>
- </project>
直接上代码RenWu.class:
- package com.zhaowu.renwu2;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import java.net.MalformedURLException;
- import java.net.URL;
- import org.jsoup.Jsoup;
- import org.jsoup.nodes.Document;
- import org.jsoup.nodes.Element;
- import org.jsoup.select.Elements;
- import com.gargoylesoftware.htmlunit.BrowserVersion;
- import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
- import com.gargoylesoftware.htmlunit.WebClient;
- import com.gargoylesoftware.htmlunit.html.HtmlInput;
- import com.gargoylesoftware.htmlunit.html.HtmlPage;
- public class RenWu {
- // 搜索页数
- private static int N = 6;
- // 搜索关键词
- private static String keyWord = "爬虫";
- // 第一页搜索结果
- private static HtmlPage firstBaiduPage;
- // Baidu对应每个搜索结果的第一页第二页第三页等等其中包含“&pn=1”,“&pn=2”,“&pn=3”等等,
- // 提取该链接并处理可以获取到一个模板,用于定位某页搜索结果
- private static String template = "";
- public static void main(String[] args) {
- goSearch(N, keyWord);
- }
- private static void goSearch(final int n, final String keyWord) {
- Thread thread = new Thread(new Runnable() {
- public void run() {
- // 页数
- int x = n;
- System.out.println("爬取百度关于关键字“" + keyWord + "”搜索结果的前" + x + "页");
- FileUtil.toFile("爬取百度关于关键字“" + keyWord + "”搜索结果的前" + x + "页\n");
- //1.获取并输出第一页百度查询内容
- Elements firstElementsLink = null;
- try {
- firstElementsLink = getFirstPage(keyWord);
- } catch (Exception e) {
- e.printStackTrace();
- }
- for (Element link : firstElementsLink) {
- // 链接url
- String linkHref = link.attr("href");
- // 链接标题
- String linkText = link.text();
- if(linkHref.length() > 13 & linkText.length() > 4) {
- String content = "链接url: " + linkHref + "\n\t链接标题: " + linkText + "\n";
- System.out.println(content);
- FileUtil.toFile(content);
- }
- }
- //2.读取第二页及之后页面预处理
- // 以firstBaiduPage作为参数,定义template,即网页格式。
- nextHref(firstBaiduPage);
- //3.获取百度第一页之后的搜索结果
- for(int i = 1; i< x; i++) {
- System.out.println("\n---------百度搜索关键字“" + keyWord + "”第" + (i + 1) + "页结果------");
- FileUtil.toFile("\n---------百度搜索关键字“" + keyWord + "”第" + (i + 1) + "页结果------" + "\n");
- // 根据已知格式修改生成新的一页的链接
- String tempURL = template.replaceAll("&pn=1", "&pn=" + i + "");
- // 显示该搜索模板
- System.out.println("\t该页地址为:" + tempURL);
- RenWu renWu = new RenWu();
- // 实现摘取网页源码
- String htmls = renWu.getPageSource(tempURL, "utf-8");
- // 网页信息转换为jsoup可识别的doc模式
- Document doc = Jsoup.parse(htmls);
- // 摘取该页搜索链接
- Elements links = doc.select("a[data-click]");
- // 该处同上getFirstPage的相关实现
- for (Element link : links) {
- // 链接url
- String linkHref = link.attr("href");
- // 链接标题
- String linkText = link.text();
- if(linkHref.length() > 13 & linkText.length() > 4) {
- String content = "链接url: " + linkHref + "\n\t链接标题: " + linkText + "\n";
- System.out.println(content);
- FileUtil.toFile(content);
- }
- }
- }
- }
- });
- thread.start();
- }
- public String getPageSource(String pageURL, String encoding) {
- // 输入:url链接&编码格式
- // 输出:该网页内容
- StringBuffer sb = new StringBuffer();
- try {
- // 构建一URL对象
- URL url = new URL(pageURL);
- // 使用openStream得到一输入流并由此构造一个BufferedReader对象
- InputStream in = url.openStream();
- InputStreamReader ir = new InputStreamReader(in);
- BufferedReader br = new BufferedReader(ir);
- String line;
- while((line = br.readLine()) != null) {
- sb.append(line);
- sb.append("\n");
- }
- br.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- return sb.toString();
- }
- /*
- * 获取百度搜索第一页内容
- */
- public static Elements getFirstPage(String keyWord) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
- //设置浏览器的User-Agent
- WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
- // HtmlUnit对JavaScript的支持不好,关闭之
- webClient.getOptions().setJavaScriptEnabled(false);
- // HtmlUnit对CSS的支持不好,关闭之
- webClient.getOptions().setCssEnabled(false);
- // 百度搜索首页页面
- HtmlPage htmlPage = webClient.getPage("http://www.baidu.com/");
- // 获取搜索输入框并提交搜索内容(查看源码获取元素名称)
- HtmlInput input = htmlPage.getHtmlElementById("kw");
- // 将搜索词模拟填进百度输入框(元素ID如上)
- input.setValueAttribute(keyWord);
- // 获取搜索按钮并点击
- HtmlInput btn = htmlPage.getHtmlElementById("su");
- // 模拟搜索按钮事件,获取第一页的html内容
- firstBaiduPage = btn.click();
- // 将获取到的百度搜索的第一页信息输出
- // 通过page.asXml()来获取百度首页的源代码,
- // 通过page.asTest()来获取页面的文字
- String content = firstBaiduPage.asXml().toString();
- // 转换为Jsoup识别的doc格式
- Document doc = Jsoup.parse(content);
- System.out.println("---------百度搜索关键字“" + keyWord + "”第1页结果--------");
- FileUtil.toFile("---------百度搜索关键字“" + keyWord + "”第1页结果--------" + "\n");
- // 返回包含类似<a......data-click=" "......>等的元素
- Elements firstElementsLink = doc.select("a[data-click]");
- // 返回此类链接,即第一页的百度搜素链接
- return firstElementsLink;
- }
- /*
- * 获取下一页地址
- */
- public static void nextHref(HtmlPage firstBaiduPage) {
- WebClient webClient = new WebClient(BrowserVersion.FIREFOX_52);
- webClient.getOptions().setJavaScriptEnabled(false);
- webClient.getOptions().setCssEnabled(false);
- // 获取到百度第一页搜索的底端的页码的html代码
- String morelinks = firstBaiduPage.getElementById("page").asXml();
- // 转换为Jsoup识别的doc格式
- Document doc = Jsoup.parse(morelinks);
- // 提取这个html中的包含<a href=""....>的部分
- Elements links = doc.select("a[href]");
- // 设置只取一次每页链接的模板格式
- boolean getTemplate = true;
- for (Element e : links) {
- // 将提取出来的<a>标签中的链接取出
- String linkHref = e.attr("href");
- if(getTemplate) {
- // 补全模板格式
- template = "http://www.baidu.com" + linkHref;
- getTemplate = false;
- }
- }
- }
- }
导出到本地文件(末尾追加)的封装方发类FileUtil.class:
- package com.zhaowu.renwu2;
- import java.io.File;
- import java.io.FileWriter;
- import java.io.IOException;
- public class FileUtil {
- public static void toFile (String content) {
- File file = null;
- FileWriter fw = null;
- file = new File("/home/acer/桌面/aaa");
- try {
- if (!file.exists()) {
- file.createNewFile();
- }
- fw = new FileWriter(file,true);
- fw.write(content);//向文件中复制内容
- fw.flush();
- } catch (IOException e) {
- e.printStackTrace();
- }finally{
- if(fw != null){
- try {
- fw.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
爬虫任务二:爬取(用到htmlunit和jsoup)通过百度搜索引擎关键字搜取到的新闻标题和url,并保存在本地文件中(主体借鉴了网上的资料)的更多相关文章
- scrapy-redis实现爬虫分布式爬取分析与实现
本文链接:http://blog.csdn.net/u012150179/article/details/38091411 一 scrapy-redis实现分布式爬取分析 所谓的scrapy-redi ...
- 网络爬虫之定向爬虫:爬取当当网2015年图书销售排行榜信息(Crawler)
做了个爬虫,爬取当当网--2015年图书销售排行榜 TOP500 爬取的基本思想是:通过浏览网页,列出你所想要获取的信息,然后通过浏览网页的源码和检查(这里用的是chrome)来获相关信息的节点,最后 ...
- 使用htmlparse爬虫技术爬取电影网页的全部下载链接
昨天,我们利用webcollector爬虫技术爬取了网易云音乐17万多首歌曲,而且还包括付费的在内,如果时间允许的话,可以获取更多的音乐下来,当然,也有小伙伴留言说这样会降低国人的知识产权保护意识,诚 ...
- python 爬虫之爬取大街网(思路)
由于需要,本人需要对大街网招聘信息进行分析,故写了个爬虫进行爬取.这里我将记录一下,本人爬取大街网的思路. 附:爬取得数据仅供自己分析所用,并未用作其它用途. 附:本篇适合有一定 爬虫基础 crawl ...
- Python爬虫之爬取慕课网课程评分
BS是什么? BeautifulSoup是一个基于标签的文本解析工具.可以根据标签提取想要的内容,很适合处理html和xml这类语言文本.如果你希望了解更多关于BS的介绍和用法,请看Beautiful ...
- Java爬虫实践--爬取CSDN网站图片为例
实现的效果,自动在工程下创建Pictures文件夹,根据网站URL爬取图片,层层获取.在Pictures下以网站的层级URL命名文件夹,用来装该层URL下的图片.同时将文件名,路径,URL插入数据库, ...
- [Python爬虫] Selenium爬取新浪微博客户端用户信息、热点话题及评论 (上)
转载自:http://blog.csdn.net/eastmount/article/details/51231852 一. 文章介绍 源码下载地址:http://download.csdn.net/ ...
- python爬虫项目-爬取雪球网金融数据(关注、持续更新)
(一)python金融数据爬虫项目 爬取目标:雪球网(起始url:https://xueqiu.com/hq#exchange=CN&firstName=1&secondName=1_ ...
- python3编写网络爬虫19-app爬取
一.app爬取 前面都是介绍爬取Web网页的内容,随着移动互联网的发展,越来越多的企业并没有提供Web页面端的服务,而是直接开发了App,更多信息都是通过App展示的 App爬取相比Web端更加容易 ...
随机推荐
- python 同时遍历多个变量
最近在用python的时候,用到遍历多个变量: import sys import math F58=11491939491.7 F=[11429229079.7,11374540753.7,1132 ...
- node.js安装与入门使用
一个基于 Chrome V8 引擎的 JavaScript 运行环境. Node.js 的包管理器 npm,是全球最大的开源库生态系统. 提供事件驱动和非阻塞I/O API,可优化应用程序的吞吐量和规 ...
- 嵌入式驱动开发之dsp 算法优化vlib emcv---算法优化
http://www.opencv.org.cn/forum.php?mod=forumdisplay&fid=9
- 一个stream!=NULL 的问题 fclose.c 47
运行一段时间会出现如下错误提示:Debug Assertion Failed!Program:...File:fseek.cline:100Expression: (stream!=NULL) 点Re ...
- 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 ...
- MathType输入补集符号的步骤有哪些
集合符号在很多的数学领域都会用到,其基本的集合运算可以分为交.并.补这三种.但是一些用户朋友们在编辑文档的时候想输入集合符号这个时候就需要用到数学公式编辑器MathType,但是很多人能够快速地编辑出 ...
- 【分享】DevDocs API Documentation
http://devdocs.io/ 这是一份综合性的在线API列表,很全,方便查找.
- React资料
基于ReactNative开发的APPhttp://reactnative.cn/cases.htmlhttp://www.cnblogs.com/qiangxia/p/5584622.html F8 ...
- const在指针中的用法
一.指向const对象的指针---对象不能修改 方式1 int value1 = 3; const int *p1 = &value1; *p1 = 5; //错误,不能修改const指向对象 ...
- 怎样開始学习ADF和Jdeveroper 11g
先给一些资料能够帮助刚開始学习的人開始学习ADF和Jdeveloper11g 1.首先毫无疑问,你要懂java语言. 能够看看Thinking In Java, 或者原来sun的网上的一些文档Sun' ...