前段時間作了一個爬取妹子套圖的小功能,小夥伴們彷佛頗有興趣,爲了還特地組建了一個Python興趣學習小組,來一塊兒學習。十個python九個爬,在你們的印象中好像Python只能作爬蟲。然而並不是如此,Python 也能夠作Web開發,接下來給你們展現一下如何作一個小說站點。html
軟件 | 版本 | 功能 | 地址 |
---|---|---|---|
Python | 3.7.1 | 腳本語言 | https://www.python.org/ |
Django | 2.1.3 | Web框架 | https://www.djangoproject.com/ |
PyCharm | 2018.2.4 | 可視化開發工具 | http://www.jetbrains.com/pycharm/ |
環境搭建說明:python
http://www.runoob.com/python3/python3-install.htmlmysql
作一個小說網站,內容是必須的,首先咱們爬取一本小說《星辰變》到數據庫。git
建立一個簡單的數據庫表:web
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
安裝數據庫驅動以及鏈接池:sql
# 數據庫驅動 pip install pymysql # 數據庫鏈接池 pip install DBUtils
代碼實現:chrome
# -*- 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/Day04django
Django 是一個開放源代碼的Web應用框架,由 Python 寫成。採用了 MVC 的框架模式,即模型M,視圖V和控制器C。它最初是被開發來用於管理勞倫斯出版集團旗下的一些以新聞內容爲主的網站的,便是CMS(內容管理系統)軟件。json
Django 框架的核心組件有:
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 # 後臺業務
控制器 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}} "><li>{{ novel.title }}</li></a> {% endfor %}
至此,一個簡單的Web項目雛形已經完成,固然還有不少須要優化的地方,小夥伴們能夠關注從零學 Python,持續更新。
源碼:https://gitee.com/52itstyle/Python/tree/master/Day06/novel