前言
前段時(shí)間做了一個(gè)爬取妹子套圖的小功能岳颇,小伙伴們似乎很有興趣投放,為了還特意組建了一個(gè)Python興趣學(xué)習(xí)小組,來(lái)一起學(xué)習(xí)疾棵。十個(gè)python九個(gè)爬,在大家的印象中好像Python只能做爬蟲痹仙。然而并非如此是尔,Python 也可以做Web開發(fā),接下來(lái)給大家展示一下如何做一個(gè)小說(shuō)站點(diǎn)开仰。
相關(guān)軟件
軟件版本功能地址Python3.7.1腳本語(yǔ)言https://www.python.org/Django2.1.3Web框架https://www.djangoproject.com/PyCharm2018.2.4可視化開發(fā)工具http://www.jetbrains.com/pycharm/
環(huán)境搭建說(shuō)明:
http://www.runoob.com/python3/python3-install.html
爬取數(shù)據(jù)
做一個(gè)小說(shuō)網(wǎng)站拟枚,內(nèi)容是必須的,首先我們爬取一本小說(shuō)《星辰變》到數(shù)據(jù)庫(kù)众弓。
創(chuàng)建一個(gè)簡(jiǎn)單的數(shù)據(jù)庫(kù)表:
CREATE TABLE `novel` (
? `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主鍵',
? `title` varchar(100) NOT NULL COMMENT '標(biāo)題',
? `content` text NOT NULL COMMENT '內(nèi)容',
? PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
安裝數(shù)據(jù)庫(kù)驅(qū)動(dòng)以及連接池:
# 數(shù)據(jù)庫(kù)驅(qū)動(dòng)
pip install pymysql
# 數(shù)據(jù)庫(kù)連接池
pip install DBUtils
代碼實(shí)現(xiàn):
# -*- coding: UTF-8 -*-
# 導(dǎo)入requests庫(kù)
import requests
# 導(dǎo)入文件操作庫(kù)
import codecs
from bs4 import BeautifulSoup
import sys
import mysql_DBUtils
from mysql_DBUtils import MyPymysqlPool
import importlib
importlib.reload(sys)
# 給請(qǐng)求指定一個(gè)請(qǐng)求頭來(lái)模擬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標(biāo)簽id屬性content的內(nèi)容 \xa0 是不間斷空白符
? ? content = texts[0].text.replace('\xa0' * 4, '\n')
? ? return content
# 寫入數(shù)據(jù)庫(kù)
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實(shí)現(xiàn)
Django 是一個(gè)開放源代碼的Web應(yīng)用框架恩溅,由 Python 寫成。采用了 MVC 的框架模式谓娃,即模型M脚乡,視圖V和控制器C。它最初是被開發(fā)來(lái)用于管理勞倫斯出版集團(tuán)旗下的一些以新聞內(nèi)容為主的網(wǎng)站的滨达,即是CMS(內(nèi)容管理系統(tǒng))軟件每窖。
Django 框架的核心組件有:
用于創(chuàng)建模型的對(duì)象關(guān)系映射
為最終用戶設(shè)計(jì)的完美管理界面
一流的 URL 設(shè)計(jì)
設(shè)計(jì)者友好的模板語(yǔ)言
緩存系統(tǒng)
創(chuàng)建項(xiàng)目
pip install Django
# 創(chuàng)建一個(gè)項(xiàng)目
python? django-admin.py startproject itstyle
# 切換目錄
cd itstyle
# 創(chuàng)建App
python manage.py startapp novel
一般一個(gè)項(xiàng)目有多個(gè)app, 當(dāng)然通用的app也可以在多個(gè)項(xiàng)目中使用,然后啟動(dòng)服務(wù):
# 默認(rèn)端口是8000
python manage.py runserver
如果提示端口被占用弦悉,可以用其它端口:
python manage.py runserver 8001
項(xiàng)目結(jié)構(gòu)
最終代碼窒典,如下:
│? manage.py
│?
├─novel
│? │? settings.py? # 基礎(chǔ)配置
│? │? urls.py? ? # URL映射
│? │? wsgi.py
│? │? __init__.py
│? │?
│? ? ? ? ?
├─templates? ? ? ? ? ? # 相關(guān)頁(yè)面
│? ? ? novel.html? ? ? ? # 章節(jié)
│? ? ? novel_list.html? ? # 小說(shuō)首頁(yè)
├─utils
│? │? dbMysqlConfig.cnf? ? # 數(shù)據(jù)庫(kù)配置參數(shù)
│? │? encoder.py? ? ? ? ? # 編碼類
│? │? mysql_DBUtils.py? ? ? # 數(shù)據(jù)庫(kù)連接池
└─view
? ? │? index.py? # 后臺(tái)業(yè)務(wù)
要點(diǎn)備注
RESTful 風(fēng)格
控制器 urls.py
from django.conf.urls import url
from django.urls import path
from view import index
urlpatterns = [
? ? # 《星辰變》首頁(yè)List
? ? path('', index.main),? # new
? ? # 章節(jié)頁(yè)面 正則匹配
? ? path('chapter/<int:novel_id>/', index.chapter),? ? # new
]
代碼實(shí)現(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)
'''
單個(gè)章節(jié)
此處 novel_id 對(duì)應(yīng) urls.py 中的 <int:novel_id>
你可以訪問(wèn):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)
恩恩 好的 這是我們免費(fèi)的直播地址 正對(duì)開發(fā)兩到八年的人群的
https://ke.qq.com/course/260263
報(bào)名截個(gè)圖給我確認(rèn)一下先? 我統(tǒng)計(jì)一下人數(shù)然后發(fā)你往期視頻資料先
列表展示
基于后端返回的數(shù)據(jù),在前臺(tái)進(jìn)行展示稽莉,這里你可以把它想象成Java中的Struts2標(biāo)簽或者JSTL標(biāo)簽瀑志,當(dāng)然也有點(diǎn)Vue的意思:
{% for novel in novel_list %}
? ? <a href="/chapter/{{novel.id}} "><li>{{ novel.title }}</li></a>
{% endfor %}
小結(jié)
至此,一個(gè)簡(jiǎn)單的Web項(xiàng)目雛形已經(jīng)完成污秆,當(dāng)然還有很多需要優(yōu)化的地方劈猪,小伙伴們可以關(guān)注從零學(xué) Python,持續(xù)更新良拼。
源碼:https://gitee.com/52itstyle/Python/tree/master/Day06/novel