java爬虫抓取动态网页(爬虫科普一下对爬虫的误区、原理以及实现(组图))
优采云 发布时间: 2021-12-06 11:03java爬虫抓取动态网页(爬虫科普一下对爬虫的误区、原理以及实现(组图))
爬虫?相信很多人都熟悉这个词。简单的说就是利用工具对网页上的数据进行爬取,并进行排序和分析。照例告诉小白爬虫的误区、原理和实现。
爬虫常见误区:python=爬虫?
很多新手都会把python等同于爬虫。其实python是一种计算机编程语言。它不仅可以做爬虫,还可以构建Web应用程序。最近很火的人工智能也可以用python语言来实现。的。
爬虫的本质是抓取服务器响应浏览器的数据(原理会在下面详述)。Java、C#等不同的计算机编程语言都可以实现爬虫。
总结:python≠爬虫,python的功能远比我们想象的要强大,爬虫不仅仅只有python才有可能。
履带原理
让我们回忆一下我们访问百度时的过程:
1.在地址栏中输入网址:
肯定有人会说我以前从来没有这样做过。我一直都是用浏览器打开导航进入百度。
其实这种方式进入百度,只不过是浏览器为你输入了访问百度的链接。
2. 浏览器刷新了,百度的搜索框出现在我们面前。
当然网速不能刷新的情况就不考虑了。
在此期间,浏览器和服务器之间发生了什么?
1. 浏览器向服务器发送URL,即请求的地址。
2. 服务器收到浏览器的网络请求,开始向浏览器响应数据。
3. 浏览器接收服务器发送来的数据,进行分析,显示出来。
有兴趣的可以清除浏览器缓存,使用Fn+F12组合键打开浏览器控制台,选择NetWork菜单,可以看到页面刷新时的具体响应过程
爬虫的实现机制
1.既然浏览器可以将请求地址发送到服务器,我们也可以通过程序向服务器发起请求。
2.既然浏览器可以接收到服务器发来的数据,我们就可以模仿浏览器的解析过程,过滤得到我们想要的数据。
总结:通过我们自己的程序,不需要反复组织我们想要的数据。所有这些都是由我们的爬虫程序完成的。
Java爬虫的具体案例
目标:抓取动态模块显示的最新新闻,并将新闻内容以文件形式保存在本地。
爬取资源 1
爬取资源2
(一) 需求分析
1.新闻网首页解析,抓取部门动态模块内容
2.模拟跳转,进入各个新闻页面,抓取新闻的具体内容
3.将新闻的具体内容保存在一个文件中
(二)代码实现
1.使用maven工具,在pom.xml中导入我们爬虫依赖的jar包
org.apache.httpcomponents
httpclient
4.5.3
org.jsoup
jsoup
1.8.3
log4j
log4j
1.2.16
junit
junit
4.10
2. 做一个发送请求的简单类
package com.sxau.example;
import java.io.IOException;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
public class MyClient {
public String getContent(String url) throws ClientProtocolException, IOException {
// 创建httpclient对象
HttpClient hClient = new DefaultHttpClient();
// 设置连接超时时间,响应超时时间,以及代理服务器
hClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000)
.setParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setParameter(ConnRouteParams.DEFAULT_PROXY, new HttpHost("117.191.11.71", 8080));
// 创建get请求对象
HttpGet hGet = new HttpGet(url);
// 模拟请求,获得服务器响应的源码
HttpResponse response = hClient.execute(hGet);
// 将源码转换为字符串
String content = EntityUtils.toString(response.getEntity(), "UTF-8");
// 返回转化后的字符串
return content;
}
}
3. 做一个解析服务器数据的类
package com.sxau.example;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class MyJsoup {
public Elements getTarget(
String htmlResource,String selectCondition) {
//解析服务器发来的数据
Document doc = Jsoup.parse(htmlResource);
//对解析后的数据通过条件筛选
Elements elements = doc.select(selectCondition);
return elements;
}
}
4. 制作一个类在本地存储文件
package com.sxau.example;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class MyFileIO {
public void makeFile(String title,String txtContent) throws IOException {
//将标题左右多余的空格去掉
title = title.trim();
//拿到当前应用所在路径
String property = System.getProperty("user.dir");
//设置生成文件的路径与名称
String filePath = property + "\\src\\main\\webapp\\spidertxt\\" + title + ".txt";
//生成新文件
File txt = new File(filePath);
//将文件输入器定位到刚刚生成的新文件
FileWriter writer = new FileWriter(txt);
//将已经匹配的字符串写入文件中
writer.write(txtContent);
//刷新并关闭流
writer.flush();
writer.close();
}
}
5. 为了提高效率,创建线程并发处理
package com.sxau.example;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.jsoup.select.Elements;
/**
* 实现Runable接口
* @author Administrator
*
*/
public class MyThread implements Runnable{
private String mainUrl;
private String singleUrl;
//提供有参数的构造方法,确保进入页面时url不为空
public MyThread(String mainUrl, String singleUrl) {
this.mainUrl = mainUrl;
this.singleUrl = singleUrl;
}
/**
* 实现接口未实现的run()方法
* 通过httpclient发送请求并接收数据
* 观察html页面,使用jsoup中便捷的仿css/js选择器语法得到我们需要的内容
* 对匹配好的字符串进行优化,并进行本地存储
*/
@Override
public void run() {
// TODO 自动生成的方法存根
MyClient myClient = new MyClient();
String url=mainUrl+singleUrl;
String content;
try {
content = myClient.getContent(url);
String selectCondition1=".arti_title";
String selectCondition2=".wp_articlecontent";
MyJsoup jsoup = new MyJsoup();
Elements elements1 = jsoup.getTarget(content, selectCondition1);
Elements elements2 = jsoup.getTarget(content, selectCondition2);
String html1 = elements1.get(0).html();
String title = html1.replaceAll("", "");
String html2 = elements2.get(0).html();
html2 = html2.replaceAll("<p>", "");
String word = html2.replaceAll("", "");
MyFileIO fileIO=new MyFileIO();
fileIO.makeFile(title, word);
} catch (ClientProtocolException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
</p>
6.制作主程序
package com.sxau.example;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class MySpider {
public static void main(String[] args) throws ClientProtocolException, IOException {
MyClient myClient = new MyClient();
String url="http://news.sxau.edu.cn/";
String content = myClient.getContent(url);
String selectCondition="a[href][title~=(|)]";
MyJsoup jsoup = new MyJsoup();
Elements elements = jsoup.getTarget(content, selectCondition);
for (Element element : elements) {
String attr = element.attr("href");
new Thread(new MyThread(url, attr)).start();
}
System.out.println("文件爬虫成功!");
}
}
6.运行mian方法,稍等片刻,刚出炉的文件已经静静的躺在文件夹里了。
log4j:WARN No appenders could be found for logger (org.apache.http.impl.conn.BasicClientConnectionManager).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
文件爬虫成功!
最终效果
至此,一个简单的爬虫功能已经实现。菜鸟们,有什么问题,欢迎大家赐教,互相探讨,共同进步。