分享一个Java爬虫实战,全网博文爬取
简介
一键爬取
<dependency>
<groupId>com.kotcrab.remarkgroupId>
<artifactId>remarkartifactId>
<version>1.2.0version>
dependency>
CREATE TABLE `app_blog_crawl` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
`type` VARCHAR(255) NOT NULL COMMENT '类型',
`url` VARCHAR(255) NOT NULL COMMENT '网址',
`title` VARCHAR(255) NOT NULL COMMENT '标题元素',
`content` VARCHAR(255) NOT NULL COMMENT '内容元素',
`gmt_create` DATETIME NOT NULL COMMENT '创建时间',
`gmt_modified` DATETIME NOT NULL COMMENT '修改时间',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8
/**
* 爬取-爪哇笔记
* 1)获取数据库配置
* 2)根据数据库配置读取文章相关元素
* 3)富文本转MD,并返回前端实体内容
* 源码:https://gitee.com/52itstyle/SPTools
* @param url
* @return
*/
@RequestMapping("crawl")
public Result crawl(String url) {
try {
String domain = JsoupUtils.getDomain(url);
String nativeSql = "SELECT * FROM app_blog_crawl WHERE url = ?";
AppBlogCrawl crawl =
dynamicQuery.nativeQuerySingleResult(AppBlogCrawl.class,nativeSql,new Object[]{domain});
if(crawl!=null){
Document document = JsoupUtils.getDocument(url);
String title = document.select(crawl.getTitle()).text();
String content = document.select(crawl.getContent()).html();
Remark remark = new Remark();
String markdown = remark.convertFragment(content);
AppBlog blog = new AppBlog();
blog.setTitle(title);
blog.setContent(markdown);
blog.setUrl(url);
return Result.ok(blog);
}else{
return Result.error("目前暂不支持此网站抓取");
}
} catch (Exception e) {
return Result.error("抓取异常");
}
}
/**
* 工具类
*/
public class JsoupUtils {
/**
* 获取 document
* @param url
* @return
* @throws IOException
*/
public static Document getDocument(String url) throws IOException {
Document document = Jsoup.connect(url)
.timeout(100000)
.ignoreContentType(true)
.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36")
.get();
return document;
}
/**
* 获取域名
* @param url
* @return
*/
public static String getDomain(String url) {
return url.split("/")[0]+"//"+url.split("/")[2];
}
}
预览
小结
— 【 THE END 】— 本公众号全部博文已整理成一个目录,请在公众号里回复「m」获取! 3T技术资源大放送!包括但不限于:Java、C/C++,Linux,Python,大数据,人工智能等等。在公众号内回复「1024」,即可免费获取!!
评论