利用Python如何實現(xiàn)一個小說網(wǎng)站雛形
前言
最近做了一個爬取妹子套圖的小功能,小伙伴們似乎很有興趣,為了還特意組建了一個Python興趣學(xué)習(xí)小組,來一起學(xué)習(xí)。十個python九個爬,在大家的印象中好像Python只能做爬蟲。然而并非如此,Python 也可以做Web開發(fā),接下來給大家展示一下如何做一個小說站點。
下面話不多說了,來一起看看詳細的介紹吧
相關(guān)軟件
| 軟件 | 版本 | 功能 | 地址 |
|---|---|---|---|
| Python | 3.7.1 | 腳本語言 | https://www.python.org/ |
| Django | 2.1.3 | Web框架 | https://www.djangoproject.com/ |
| PyCharm | 2018.2.4 | 可視化開發(fā)工具 | http://www.jetbrains.com/pycharm/ |
環(huán)境搭建說明:
linux下安裝python3環(huán)境:http://www.dbjr.com.cn/article/109580.htm
Window 64位下python3.6.2環(huán)境搭建圖文教程:http://www.dbjr.com.cn/article/147707.htm
爬取數(shù)據(jù)
做一個小說網(wǎng)站,內(nèi)容是必須的,首先我們爬取一本小說《星辰變》到數(shù)據(jù)庫。
創(chuàng)建一個簡單的數(shù)據(jù)庫表:
CREATE TABLE `novel` ( `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主鍵', `title` varchar(100) NOT NULL COMMENT '標題', `content` text NOT NULL COMMENT '內(nèi)容', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
安裝數(shù)據(jù)庫驅(qū)動以及連接池:
# 數(shù)據(jù)庫驅(qū)動 pip install pymysql # 數(shù)據(jù)庫連接池 pip install DBUtils
代碼實現(xiàn):
# -*- coding: UTF-8 -*-
# 導(dǎo)入requests庫
import requests
# 導(dǎo)入文件操作庫
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")
# 獲取章節(jié)內(nèi)容
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的內(nèi)容 \xa0 是不間斷空白符
content = texts[0].text.replace('\xa0' * 4, '\n')
return content
# 寫入數(shù)據(jù)庫
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')
# 獲取所有的章節(jié)
a = soup.find('div', id='list').find_all('a')
print('總章節(jié)數(shù): %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實現(xiàn)
Django 是一個開放源代碼的Web應(yīng)用框架,由 Python 寫成。采用了 MVC 的框架模式,即模型M,視圖V和控制器C。它最初是被開發(fā)來用于管理勞倫斯出版集團旗下的一些以新聞內(nèi)容為主的網(wǎng)站的,即是CMS(內(nèi)容管理系統(tǒng))軟件。
Django 框架的核心組件有:
- 用于創(chuàng)建模型的對象關(guān)系映射
- 為最終用戶設(shè)計的完美管理界面
- 一流的 URL 設(shè)計
- 設(shè)計者友好的模板語言
- 緩存系統(tǒng)
創(chuàng)建項目
pip install Django # 創(chuàng)建一個項目 python django-admin.py startproject itstyle # 切換目錄 cd itstyle # 創(chuàng)建App python manage.py startapp novel
一般一個項目有多個app, 當然通用的app也可以在多個項目中使用,然后啟動服務(wù):
# 默認端口是8000 python manage.py runserver
如果提示端口被占用,可以用其它端口:
python manage.py runserver 8001
項目結(jié)構(gòu)
最終代碼,如下:
│ manage.py
│
├─novel│ │ settings.py # 基礎(chǔ)配置
│ │ urls.py # URL映射
│ │ wsgi.py
│ │ __init__.py
│ │
│
├─templates # 相關(guān)頁面
│ novel.html # 章節(jié)
│ novel_list.html # 小說首頁
├─utils
│ │ dbMysqlConfig.cnf # 數(shù)據(jù)庫配置參數(shù)
│ │ encoder.py # 編碼類
│ │ mysql_DBUtils.py # 數(shù)據(jù)庫連接池
└─view
│ index.py # 后臺業(yè)務(wù)
要點備注
RESTful 風(fēng)格
控制器 urls.py
from django.conf.urls import url
from django.urls import path
from view import index
urlpatterns = [
# 《星辰變》首頁List
path('', index.main), # new
# 章節(jié)頁面 正則匹配
path('chapter/<int:novel_id>/', index.chapter), # new
]
代碼實現(xiàn):
from django.http import HttpResponse
from django.shortcuts import render
from utils.mysql_DBUtils import mysql
# 《星辰變》章節(jié)列表
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)
'''
單個章節(jié)
此處 novel_id 對應(yīng) 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)
列表展示
基于后端返回的數(shù)據(jù),在前臺進行展示,這里你可以把它想象成Java中的Struts2標簽或者JSTL標簽,當然也有點Vue的意思:
{% for novel in novel_list %}
<a href="/chapter/{{novel.id}} " rel="external nofollow" ><li>{{ novel.title }}</li></a>
{% endfor %}
小結(jié)
至此,一個簡單的Web項目雛形已經(jīng)完成,當然還有很多需要優(yōu)化的地方,小伙伴們可以關(guān)注從零學(xué) Python,持續(xù)更新。
源碼:https://gitee.com/52itstyle/Python/tree/master/Day06/novel (本地下載)
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
Python pandas軸旋轉(zhuǎn)stack和unstack的使用說明
這篇文章主要介紹了Python pandas軸旋轉(zhuǎn)stack和unstack的使用說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03

