一、摘要:

使用python爬取网络小说数据存入数据库,利用C3P0数据库连接池获取数据库数据,采用MVC三层架构对数据库数据进行操作,输出JSON格式数据到前端页面

二、内容:

1.gitee外链消失,故删除

2.核心源码分析

2.1 通过Python爬取小说数据存入数据库

import os
from time import sleep
import requests
import parsel
from parsel import Selector #请求网页html数据
import pymysql #请求数据库 # 从chapter_url中得到小说的名字对应的xiaoshuoid chapter_urlshuzu[4],然后从章节中得到zhangjieid chapter_urlshuzu[5].split('.')[0],章节内容是for循环里所有 利用test 和章节名称就是title好拿
def download_one_chapter(chapter_url,bookname,lebieming): #爬取单一章节内容代码块,函数
response=requests.get(chapter_url)
chapter_urlshuzu=chapter_url.split('/') #拆分章节url,通过切片获取需要的信息
response.encoding=response.apparent_encoding #字符编码 自动识别
# response.encoding = 'utf-8' 手动改变字符编码
# 提取网页内容的方法:正则表达式:提取字符串 xpath css选择器 提取网页数据结构(html) 语法糖 或者 lxml pyquery parsel sel=Selector(response.text) # 提取网页小说内容
title=sel.css('h1::text').get()
f=open('biquge/'+lebieming+'/'+bookname+'/'+title+'.txt',mode='w',encoding='utf-8') # f 打开的文件对象 打开文件,创建文件
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:
# 处理每行\n
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() # xiaoshuoming就是bookname xiaoshuoid就是book_url里的参数book_urlshuzu[4] xiaoshuofenleiid就是用lebieming对应数组来取leibieshuzu.index(lebieming)+1
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()
# 限制不下载前十二章
# print(index)
# for line in index:
# i+=1
# # print('http://www.shuquge.com/txt/'+ book_urlshuzu[4]+'/'+line)
# if i>12:
# download_one_chapter('http://www.shuquge.com/txt/'+ book_urlshuzu[4]+'/'+line,bookname,lebieming)
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
 //获取当前book路由下的方法
String method = req.getParameter("method");
System.out.println("BookServlet中使用方法为:" + method);
Gson gson = new Gson();
String json="";
List<NovelInfo> list=new ArrayList<>();
//如果为空默认使用findAll方法
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;
//需要执行的sql语句
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

Python爬取小说+Servlet+C3P0+MVC构建小说api的更多相关文章

  1. python 爬取qidian某一页全部小说

      本文纯粹用于技术练习,请勿用作非法途径 import re import urllib.request from bs4 import BeautifulSoup import time url= ...

  2. python爬取+使用网易卡搭作品数量api

    第一步,当然是打开浏览器~ 然后打开卡搭~ 看着熟悉的界面,是不是有点不知所措? 这就对了,咱找点事情干干. 随便找个倒霉蛋,比如这位:"混世大王",打开他的主页! 按下f12(我 ...

  3. python入门学习之Python爬取最新笔趣阁小说

    Python爬取新笔趣阁小说,并保存到TXT文件中      我写的这篇文章,是利用Python爬取小说编写的程序,这是我学习Python爬虫当中自己独立写的第一个程序,中途也遇到了一些困难,但是最后 ...

  4. python 爬取王者荣耀高清壁纸

    代码地址如下:http://www.demodashi.com/demo/13104.html 一.前言 打过王者的童鞋一般都会喜欢里边设计出来的英雄吧,特别想把王者荣耀的英雄的高清图片当成电脑桌面 ...

  5. python爬取博客圆首页文章链接+标题

    新人一枚,初来乍到,请多关照 来到博客园,不知道写点啥,那就去瞄一瞄大家都在干什么好了. 使用python 爬取博客园首页文章链接和标题. 首先当然是环境了,爬虫在window10系统下,python ...

  6. python 爬取豆瓣书籍信息

    继爬取 猫眼电影TOP100榜单 之后,再来爬一下豆瓣的书籍信息(主要是书的信息,评分及占比,评论并未爬取).原创,转载请联系我. 需求:爬取豆瓣某类型标签下的所有书籍的详细信息及评分 语言:pyth ...

  7. python爬取《龙岭迷窟》的数据,看看质量剧情还原度到底怎么样

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:简单 PS:如有需要Python学习资料的小伙伴可以加点击下方链接自行 ...

  8. 手把手教你使用Python爬取西刺代理数据(下篇)

    /1 前言/ 前几天小编发布了手把手教你使用Python爬取西次代理数据(上篇),木有赶上车的小伙伴,可以戳进去看看.今天小编带大家进行网页结构的分析以及网页数据的提取,具体步骤如下. /2 首页分析 ...

  9. Python 爬取所有51VOA网站的Learn a words文本及mp3音频

    Python 爬取所有51VOA网站的Learn a words文本及mp3音频 #!/usr/bin/env python # -*- coding: utf-8 -*- #Python 爬取所有5 ...

  10. python爬取网站数据

    开学前接了一个任务,内容是从网上爬取特定属性的数据.正好之前学了python,练练手. 编码问题 因为涉及到中文,所以必然地涉及到了编码的问题,这一次借这个机会算是彻底搞清楚了. 问题要从文字的编码讲 ...

随机推荐

  1. 在项目中使用UEditor碰到的几个问题

    1.文本编辑器的下拉框无法使用.即选择字号字体的下拉选择框无法使用. 通过调试,发现不是编辑器的下拉框没有出来,而是下拉框显示在弹出框的底部,猜测是否和z-index属性有关. 产生这个问题的原因是文 ...

  2. $KMP$学习记

    <不浪漫罪名>--王杰 没有花 这刹那被破坏吗 无野火都会温暖吗 无烟花一起庆祝好吗 若爱恋 仿似戏剧那样假 如布景一切都美化 连相拥都参照主角吗 你说我未能定时 令你每天欢笑一次 我没说 ...

  3. Unity Shader中的常见流控制指令

    在Shader中处理流控制语句时,常加上一些宏去处理流控制指令.例如: [UNITY_UNROLL] for (int i = 0; i < 10; i++) { //do something. ...

  4. Nokia 5GC 产品概览

    目录 文章目录 目录 Nokia SR OS Nokia NSP NFM-P Nokia 7750 SR-MG 5G User Plane Forwarding Mobile Gateway Non- ...

  5. pageoffice 6 实现数据区域填充(插入文本、图片、word、excel等)

    在实际的Word文档开发中,经常需要自动填充数据到Word模板中,以生成动态的Word文档. 例如: 1.我们可以根据数据库表中已保存的个人信息,设计好一个简历模板docx文件,然后通过代码将这些个人 ...

  6. 腾讯云服务器sdk

    参考:https://cloud.tencent.com/document/product/494/7244 pip install -i https://mirrors.tencent.com/py ...

  7. MySQL面试必备三之事务

    本文首发于公众号:Hunter后端 原文链接:MySQL面试必备三之事务 这一篇笔记介绍一下 MySQL 的事务,面试中常被问到关于事务的几个问题如下: 事务是什么 为什么需要事务,事务有什么作用 事 ...

  8. MySQL查询某个字段含有字母数字的值

    1.正则表达式(REGEXP) 查询MySQL表中某个字段含有字母和数字的值,可以使用正则表达式(REGEXP)来匹配这样的模式.在MySQL中,正则表达式是一个强大的工具,可以用来搜索和匹配字符串中 ...

  9. 深入探讨Function Calling:实现外部函数调用的工作原理

    引言 Function Calling 是一个允许大型语言模型(如 GPT)在生成文本的过程中调用外部函数或服务的功能. Function Calling允许我们以 JSON 格式向 LLM 模型描述 ...

  10. 理解Vue 3响应式系统原理

    title: 理解Vue 3响应式系统原理 date: 2024/5/28 15:44:47 updated: 2024/5/28 15:44:47 categories: 前端开发 tags: Vu ...