采用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,并保存在本地文件中(主体借鉴了网上的资料)的更多相关文章

  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. uvalive 3231 Fair Share 公平分配问题 二分+最大流 右边最多流量的结点流量尽量少。

    /** 题目: uvalive 3231 Fair Share 公平分配问题 链接:https://vjudge.net/problem/UVALive-3231 题意:有m个任务,n个处理器,每个任 ...

  2. struts2中,OGNL访问值栈的时候查找的顺序是什么?请排序:模型对象、临时对象、固定名称的对象、Action对象

    struts2中,OGNL访问值栈的时候查找的顺序是什么?请排序:模型对象.临时对象.固定名称的对象.Action对象 解答:struts2的值栈排列顺序为:1).临时对象:2).模型对象:3).Ac ...

  3. shell面试题总结

    1) 如何向脚本传递参数 ? ./script argument 例子: 显示文件名称脚本 ./show.sh file1.txt cat show.sh #!/bin/bash echo $1 (L ...

  4. Windows下MySQL配置及安全加固总结

    Windows下MySQL配置及安全加固总结 在网管的实际使用过程中,MySQL数据库在安装后的配置及安全加固内容,在客户中逐渐要求越来越高.从反馈的问题看,一般都是由第三方软件公司的软件扫描整个系统 ...

  5. hdu2469(计算几何)

    枚举所有可能的半径,然后将所有满足这个半径的点按角度(与x轴正半轴的夹角)排序. 然后一遍扫描求出在这个半径下选k个点所需的最小面积 . 思路还是比较简单,实现略有些繁琐. 要先将点的坐标转换为角度. ...

  6. 深入理解--SSM框架中Dao层,Mapper层,controller层,service层,model层,entity层都有什么作用

    SSM是sping+springMVC+mybatis集成的框架. MVC即model view controller. model层=entity层.存放我们的实体类,与数据库中的属性值基本保持一致 ...

  7. jq 选择器基础及拓展

    jquery 用的很多,所以jq的选择器就很受欢迎,但是用的过程中有一些小问题,如果不点透就永远不知道. 1:ID选择器:$("#ID"); 得到一个指定对应,并且只能得到一个对象 ...

  8. Android性能测试摘入(TestHome)

    Android性能测试:      客户端性能测试      服务端性能测试   客户端性能测试:      1.ROM版本的性能测试(即手机的不同操作系统):关注功耗测试      2.应用的性能测 ...

  9. ZOJ 3331 Process the Tasks(双塔DP)

    Process the Tasks Time Limit: 1 Second      Memory Limit: 32768 KB There are two machines A and B. T ...

  10. pip安装Scrapy框架报错

    安装: pip3 install scrapy==1.1.0rc3 一..解决scrapy安装错误: 二.具体操作: 1.在http://landinghub.visualstudio.com/vis ...