本篇博文主要讲述如何自动新建图书分类文件夹。
数据来源于中国图书馆分类法。
技术:jsoup爬虫
处理流程:
1.抓取网站数据获取图书种类树。
2.打印目录结构
3.创建目录结构
中国图书馆分类法
代码如下:
package com.gugu.book;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class MDBookDir {
// 种子地址
private static final String url = "http://www.ztflh.com/?c=33314";
// 分隔符
private static String sepa = java.io.File.separator;
private static final String basePath = "E:"+sepa+"book"; // 如果使用转义符CMD不认
// 每个节点id
static int id = 0;
// 所有图书种类的列表
static List<BookTypeTree> bookTreeList = new ArrayList<BookTypeTree>();
public static void main(String[] args) throws IOException {
// 获取图书类型树数据
getBookTypeInfo(url, 0);
// 打印内容,可以粘贴进bat批量执行
printlnBookList();
// 创建树结构
mkdirBookList();
}
private static void mkdirBookList() {
for (BookTypeTree bookTypeNode: bookTreeList) {
File file = new File(bookTypeNode.path);
file.mkdirs();
}
}
public static void getBookTypeInfo(String url, int parentId) throws IOException{
Document document = Jsoup.connect(url).timeout(3000000).get();
Element listE = document.getElementById("list"); // 获取图书种类列表
if(null == listE){
// 到叶子节点,结束本次递归
return;
}
Elements lis = listE.getElementsByTag("li");
//获取所有对象图书种类
for (Element li : lis) {
id += 1;
// 输出当前路径
String name = li.text();
String path = getPath(parentId) + sepa + name;
BookTypeTree bookNode = new BookTypeTree(id, parentId, name, path);
bookTreeList.add(bookNode);
// 获取子种类url
String urlAddress = li.select("a").first().attr("href");
// 递归子种类
getBookTypeInfo(urlAddress, id);
}
}
// 打印显示列表
static void printlnBookList(){
for (BookTypeTree bookTypeNode: bookTreeList) {
// System.out.println(bookTypeNode.toString());
System.out.println("MD " + bookTypeNode.path);
}
}
static String getPath(int id){
if(id == 0){
return basePath;
}
for (BookTypeTree bookTypeNode: bookTreeList) {
if(id == bookTypeNode.id){
return bookTypeNode.path;
}
}
return null;
}
}
class BookTypeTree{
int id;
int parentId;
String name;
String path;
public BookTypeTree(int id, int parentId, String name, String path) {
this.id=id;
this.parentId=parentId;
this.name=name;
this.path=path;
}
@Override
public String toString() {
return "BookTypeTree [id=" + id + ", parentId=" + parentId + ", name=" + name + ", path=" + path + "]";
}
}
创建目录