package com.html;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* 利用java的jsoup开发搜索引擎爬虫
*
* @author 80695
* @version $Id: HtmlJsoup.java, v 0.1 2017年6月18日 上午10:22:32 80695 Exp $
*/
public class HtmlJsoup {
/**
* 根据网址和页面的编码集获取网页的源代码
* @param url url 需要下载url地址
* @param encoding 网页的编码集
* @return String 网页的源代码
*/
public static String getHtmlResourceByUrl(String url, String encoding) {
//声明一个存储网页源代码的容器
StringBuffer buffer = new StringBuffer();
URL urlObj = null;
URLConnection uc = null;
InputStreamReader in = null;
BufferedReader reader = null;
try {
//建立网络链接
urlObj = new URL(url);
//打开网络连接
uc = urlObj.openConnection();
//简历网络的输入流
in = new InputStreamReader(uc.getInputStream(), encoding);
//缓冲写入的文件流
reader = new BufferedReader(in);
//临时变量
String tempLine = null;
//循环读取文件流
while ((tempLine = reader.readLine()) != null) {
buffer.append(tempLine + "\n");//循环不断的追加数据
}
} catch (Exception e) {
e.getStackTrace();
System.err.println("connection timeOut...");
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return buffer.toString();
}
/**
* 根据一个图片的Url地址,通过这个URL批量下载图片到服务器的磁盘
*
* @param imgURL
*/
public static void downImages(String imgURL, String filePath) {
String fileName = imgURL.substring(imgURL.lastIndexOf("/"));
//创建文件的目录
try {
File files = new File(filePath);
//判断是否存在文件夹
if (!files.exists()) {
files.mkdirs();
}
//获取图片文件的下载地址
URL url = new URL(imgURL);
//连接网路图片地址
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
//获取连接的输出流
InputStream is = uc.getInputStream();
//创建文件
File file = new File(filePath + fileName);
//创建输出流,写入问件
FileOutputStream out = new FileOutputStream(file);
int i = 0;
while ((i = is.read()) != -1) {
out.write(i);
}
is.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
public static void main(String[] args) {
System.out.println("系统运行开始");
//根据网址和页面的编码集获取网页的源代码
String htmlResource = getHtmlResourceByUrl(
"www.baidu.com",
"utf-8");
//System.out.println(htmlResource);
//解析源代码
Document document = Jsoup.parse(htmlResource);
//获取网页的图片
//图片标签
Elements elements = document.getElementsByTag("script");
for (Element element : elements) {
String imgSrc = element.attr("src");
String imgPath = imgSrc;
System.out.println("下载" + imgSrc + "开始");
if (!StringUtil.isBlank(imgPath)) {
downImages(imgPath, "F:\\learnCode\\ing\\");
}
}
/* Element element = document.getElementById("myAudio");
System.out.println(element);*/
System.out.println("图片下载成功!!!!!");
//解析我们需要下载的内容部分
}
}