一、摘要:
使用python爬取网络小说数据存入数据库,利用C3P0数据库连接池获取数据库数据,采用MVC三层架构对数据库数据进行操作,输出JSON格式数据到前端页面
二、内容:
1.gitee外链消失,故删除
2.核心源码分析
2.1 通过Python爬取小说数据存入数据库
import os
from time import sleep
import requests
import parsel
from parsel import Selector
import pymysql
def download_one_chapter(chapter_url,bookname,lebieming):
response=requests.get(chapter_url)
chapter_urlshuzu=chapter_url.split('/')
response.encoding=response.apparent_encoding
sel=Selector(response.text)
title=sel.css('h1::text').get()
f=open('biquge/'+lebieming+'/'+bookname+'/'+title+'.txt',mode='w',encoding='utf-8')
f.write(title)
for line in sel.css('#content::text').getall():
print(line.strip(),file=f)
f.close()
conn = pymysql.connect(host='localhost',port=3306,user='root',passwd='123456',db='xiaoshuo',charset='utf8',)
cursor = conn.cursor()
f = open('biquge/' + lebieming + '/' + bookname + '/' + title + '.txt', mode='r', encoding='utf-8')
while True:
line = f.readlines()
if line:
line = "".join(line)
line = line.strip('\n')
line = line.split(",")
content = line[0]
cursor.execute(
"insert into zhangjie(zhangjieid,zhangjiename,zhangjieleirong,xiaoshuoid) values(%s,%s,%s,%s)",
[chapter_urlshuzu[5].split('.')[0],title,content,chapter_urlshuzu[4]])
else:
break
f.close()
cursor.close()
conn.commit()
conn.close()
def download_one_book(book_url,bookname,lebieming):
response=requests.get(book_url)
book_urlshuzu=book_url.split('/')
response.encoding=response.apparent_encoding
sel=Selector(response.text)
if os.path.exists('biquge/' + lebieming + '/' + bookname):
print("已存储有" + bookname + "小说")
return
if not os.path.exists('biquge/' + lebieming + '/' + bookname):
os.mkdir('biquge/' +lebieming+'/'+ bookname)
leibieshuzu=['玄幻','武侠','都市','历史','侦探','网游','科幻']
xiaoshuoimg='http://www.shuquge.com/files/article/image/'+book_urlshuzu[4][0:len(book_urlshuzu[4])-3]+'/'+book_urlshuzu[4]+'/'+book_urlshuzu[4]+'s.jpg'
conn = pymysql.connect(host='localhost',port=3306,user='root',passwd='123456',db='xiaoshuo',charset='utf8',)
cursor = conn.cursor()
cursor.execute(
"insert into xiaoshuoinfo(xiaoshuoid,xiaoshuoname,xiaoshuofenleiid,xiaoshuoimg) values(%s,%s,%s,%s)",
[book_urlshuzu[4],bookname,leibieshuzu.index(lebieming)+1,xiaoshuoimg])
cursor.close()
conn.commit()
conn.close()
i=0;
index=sel.css('.listmain a::attr(href)').getall()
download_one_chapter('http://www.shuquge.com/txt/'+ book_urlshuzu[4]+'/'+index[12],bookname,lebieming)
download_one_chapter('http://www.shuquge.com/txt/'+ book_urlshuzu[4]+'/'+index[13],bookname,lebieming)
print("读取"+bookname+"小说完成")
def download_category(category_url,leibieming):
response = requests.get(category_url)
response.encoding = response.apparent_encoding
sel = Selector(response.text)
os.mkdir('biquge/' + leibieming)
if os.path.exists('biquge/' + leibieming):
index2 = sel.css('span.s2 a::text').getall()
i=0
index = sel.css('span.s2 a::attr(href)').getall()
for line in index:
download_one_book(line,index2[i],leibieming)
i+=1
def download_allcategory(website_url):
response = requests.get(website_url)
response.encoding = response.apparent_encoding
sel = Selector(response.text)
index2 = sel.css('.nav a::text').getall()
i=1
j=1
index = sel.css('.nav a::attr(href)').getall()
for line in index:
if i>=8:
break
if j!=0 and j<8:
print(line)
download_category(line, index2[i])
i+=1
j+=1
download_allcategory('http://www.shuquge.com/')
2.2 获取所有小说信息
2.2.1 Controller—BookServlet
String method = req.getParameter("method");
System.out.println("BookServlet中使用方法为:" + method);
Gson gson = new Gson();
String json="";
List<NovelInfo> list=new ArrayList<>();
if (method == null) {
method = "findAllBook";
}
switch(method){
case "findAllBook":
list=bookService.findAllBook();
json = gson.toJson(list);
break;
}
2.2.2 Service—BookService
public interface BookService {
public List<NovelInfo> findAllBook();
}
public class BookServiceImpl implements BookService {
private BookRepository bookRepository=new BookRepositoryImpl();
@Override
public List<NovelInfo> findAllBook() {
return bookRepository.findAllBook();
}
}
2.2.3 Repository—Book Repository
public interface BookRepository {
public List<NovelInfo> findAllBook();
}
public class BookRepositoryImpl implements BookRepository {
List<NovelInfo> list=new ArrayList<>();
@Override
public List<NovelInfo> findAllBook() {
Connection connection= JdbcTools.getConnection();
PreparedStatement statement=null;
ResultSet resultSet =null;
String sql="SELECT * FROM xiaoshuoinfo";
try {
statement=connection.prepareStatement(sql);
resultSet=statement.executeQuery();
while (resultSet.next()){
list.add(new NovelInfo(resultSet.getString(1),resultSet.getString(2),resultSet.getString(3),resultSet.getString(4)));
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
JdbcTools.release(connection,statement,resultSet);
}
return list;
}
}
2.3 其他
根据小说种类ID获取该种类所有小说信息,获取小说所有种类,获取所有小说章节,获取一本小说所有章节,根据小说ID获取该小说信息参看源码链接
python爬取小说
小说api
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律