自己開發了一款小說網站!師傅說這個專案做外包可以拿3W?
阿新 • • 發佈:2018-11-27
環境搭建說明:
http://www.runoob.com/python3/python3-install.html
爬取資料
做一個小說網站,內容是必須的,首先我們爬取一本小說《星辰變》到資料庫。
建立一個簡單的資料庫表:
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, ' ') 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
進群:548377875 即可獲取驚喜大禮包哦!
建立專案
# 安裝Web框架 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 import utils.mysql_DBUtils from utils.mysql_DBUtils import MyPymysqlPool from utils.encoder import MyEncoder import json mysql = MyPymysqlPool("dbMysql") # 《星辰變》章節列表 def main(request): # 這裡讀取10條,待優化分頁 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) ''' 單個章節訪問 此處 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) result['title'] = result['title'].decode('utf-8') result['content'] = result['content'].decode('utf-8') 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專案雛形已經完成,當然還有很多需要優化的地方,做成了專案,應該就能有3w快到手了!路還長,還需努力!