利用Python如何实现一个小说网站雏形
前言
最近做了一个爬取妹子套图的小功能,小伙伴们似乎很有兴趣,为了还特意组建了一个python兴趣学习小组,来一起学习。十个python九个爬,在大家的印象中好像python只能做爬虫。然而并非如此,python 也可以做web开发,接下来给大家展示一下如何做一个小说站点。
下面话不多说了,来一起看看详细的介绍吧
相关软件
软件 | 版本 | 功能 | 地址 |
---|---|---|---|
python | 3.7.1 | 脚本语言 | |
django | 2.1.3 | web框架 | |
pycharm | 2018.2.4 | 可视化开发工具 |
环境搭建说明:
linux下安装python3环境:
window 64位下python3.6.2环境搭建图文教程:
爬取数据
做一个小说网站,内容是必须的,首先我们爬取一本小说《星辰变》到数据库。
创建一个简单的数据库表:
create table `novel` ( `id` int(11) not null auto_increment comment '自增主键', `title` varchar(100) not null comment '标题', `content` text not null comment '内容', primary key (`id`) ) engine=innodb auto_increment=1 default charset=utf8
安装数据库驱动以及连接池:
# 数据库驱动 pip install pymysql # 数据库连接池 pip install dbutils
代码实现:
# -*- coding: utf-8 -*- # 导入requests库 import requests # 导入文件操作库 import codecs from bs4 import beautifulsoup import sys import mysql_dbutils from mysql_dbutils import mypymysqlpool import importlib importlib.reload(sys) # 给请求指定一个请求头来模拟chrome浏览器 headers = { 'user-agent': 'mozilla/5.0 (windows nt 10.0; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/54.0.2840.99 safari/537.36'} server = 'http://www.biquge.cm' # 星辰变地址 book = 'http://www.biquge.cm/2/2042/' # 定义db mysql = mypymysqlpool("dbmysql") # 获取章节内容 def get_contents(chapter): req = requests.get(url=chapter) html = req.content html_doc = str(html, 'gbk') bf = beautifulsoup(html_doc, 'html.parser') texts = bf.find_all('div', id="content") # 获取div标签id属性content的内容 \xa0 是不间断空白符 content = texts[0].text.replace('\xa0' * 4, '\n') return content # 写入数据库 def write_db(chapter, content): sql = "insert into novel (title, content) values(%(title)s, %(content)s);" param = {"title": chapter, "content": content} mysql.insert(sql, param) # 主方法 def main(): res = requests.get(book, headers=headers) html = res.content html_doc = str(html, 'gbk') # 使用自带的html.parser解析 soup = beautifulsoup(html_doc, 'html.parser') # 获取所有的章节 a = soup.find('div', id='list').find_all('a') print('总章节数: %d ' % len(a)) for each in a: try: chapter = server + each.get('href') content = get_contents(chapter) chapter = each.string write_db(chapter, content) except exception as e: print(e) mysql.dispose() if __name__ == '__main__': main()
更多代码详见:
https://gitee.com/52itstyle/python/tree/master/day04
web实现
django 是一个开放源代码的web应用框架,由 python 写成。采用了 mvc 的框架模式,即模型m,视图v和控制器c。它最初是被开发来用于管理劳伦斯出版集团旗下的一些以新闻内容为主的网站的,即是cms(内容管理系统)软件。
django 框架的核心组件有:
- 用于创建模型的对象关系映射
- 为最终用户设计的完美管理界面
- 一流的 url 设计
- 设计者友好的模板语言
- 缓存系统
创建项目
pip install django # 创建一个项目 python django-admin.py startproject itstyle # 切换目录 cd itstyle # 创建app python manage.py startapp novel
一般一个项目有多个app, 当然通用的app也可以在多个项目中使用,然后启动服务:
# 默认端口是8000 python manage.py runserver
如果提示端口被占用,可以用其它端口:
python manage.py runserver 8001
项目结构
最终代码,如下:
│ manage.py
│
├─novel│ │ settings.py # 基础配置
│ │ urls.py # url映射
│ │ wsgi.py
│ │ __init__.py
│ │
│
├─templates # 相关页面
│ novel.html # 章节
│ novel_list.html # 小说首页
├─utils
│ │ dbmysqlconfig.cnf # 数据库配置参数
│ │ encoder.py # 编码类
│ │ mysql_dbutils.py # 数据库连接池
└─view
│ index.py # 后台业务
要点备注
restful 风格
控制器 urls.py
from django.conf.urls import url from django.urls import path from view import index urlpatterns = [ # 《星辰变》首页list path('', index.main), # new # 章节页面 正则匹配 path('chapter/<int:novel_id>/', index.chapter), # new ]
代码实现:
from django.http import httpresponse from django.shortcuts import render from utils.mysql_dbutils import mysql # 《星辰变》章节列表 def main(request): sql = "select id,title from novel limit 10;" result = mysql.getall(sql) # result = json.dumps(result, cls=myencoder, ensure_ascii=false, indent=4) # result = json.loads(result) context = {'novel_list': result} return render(request, 'novel_list.html', context) # def chapter(request): # id = request.get['id'] # sql = "select content from novel where id = %(id)s;" # param = {"id": id} # result = mysql.getone(sql, param) # context = {'novel': result} # return render(request, 'novel.html', context) ''' 单个章节 此处 novel_id 对应 urls.py 中的 <int:novel_id> 你可以访问:http://localhost:8000/chapter/1/ ''' def chapter(request, novel_id): sql = "select title,content from novel where id = %(id)s;" param = {"id": novel_id} result = mysql.getone(sql, param) context = {'novel': result} return render(request, 'novel.html', context)
列表展示
基于后端返回的数据,在前台进行展示,这里你可以把它想象成java中的struts2标签或者jstl标签,当然也有点vue的意思:
{% for novel in novel_list %} <a href="/chapter/{{novel.id}} " rel="external nofollow" ><li>{{ novel.title }}</li></a> {% endfor %}
小结
至此,一个简单的web项目雏形已经完成,当然还有很多需要优化的地方,小伙伴们可以关注从零学 python,持续更新。
源码:https://gitee.com/52itstyle/python/tree/master/day06/novel (本地下载)
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。