Java小说爬虫程序:使用Jsoup和JDBC实现数据抓取与存储
本文介绍如何使用Java语言编写一个小说爬虫程序,利用Jsoup库抓取小说内容,并通过JDBC将数据存储到数据库中。
爬虫接口
public interface NovelCrawler {
/**
* 抓取小说内容
* @param url 小说地址
* @return 小说内容
*/
String crawlNovelContent(String url);
}
爬虫接口的实现
public class NovelCrawlerImpl implements NovelCrawler {
/**
* 抓取小说内容
* @param url 小说地址
* @return 小说内容
*/
public String crawlNovelContent(String url) {
String content = "";
try {
Document doc = Jsoup.connect(url).get();
Elements elements = doc.select('div#content');
content = elements.get(0).text();
} catch (IOException e) {
e.printStackTrace();
}
return content;
}
}
数据库操作接口
public interface NovelDao {
/**
* 保存小说内容
* @param novel 小说对象
* @return 保存成功返回true,否则返回false
*/
boolean saveNovel(Novel novel);
}
数据库操作接口的实现
public class NovelDaoImpl implements NovelDao {
/**
* 保存小说内容
* @param novel 小说对象
* @return 保存成功返回true,否则返回false
*/
public boolean saveNovel(Novel novel) {
Connection conn = null;
PreparedStatement stmt = null;
try {
// 连接数据库
conn = DriverManager.getConnection('jdbc:mysql://localhost:3306/novel', 'root', 'password');
// 插入小说数据
String sql = 'insert into novel(title, author, content) values(?, ?, ?)';
stmt = conn.prepareStatement(sql);
stmt.setString(1, novel.getTitle());
stmt.setString(2, novel.getAuthor());
stmt.setString(3, novel.getContent());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
// 关闭资源
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return true;
}
}
小说对象
public class Novel {
private String title; // 小说标题
private String author; // 小说作者
private String content; // 小说内容
// 构造函数
public Novel(String title, String author, String content) {
this.title = title;
this.author = author;
this.content = content;
}
// 小说标题的getter和setter方法
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
// 小说作者的getter和setter方法
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
// 小说内容的getter和setter方法
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
以上代码可以实现从指定URL爬取小说内容并存储到数据库中。当然,在实际项目中,还需要考虑更多的异常处理和日志记录等细节问题。
原文地址: https://www.cveoy.top/t/topic/nqgt 著作权归作者所有。请勿转载和采集!