视频链接:
Python课程天花板,Python入门+Python爬虫+Python数据分析5天项目实操/Python基础.Python教程_哔哩哔哩_bilibili
视频教程中要访问的链接:
豆瓣电影 Top 250
httpbin.org
seo推广公司网站模板_站长素材
Examples - Apache ECharts
WordCloud for Python documentation — wordcloud 1.8.1 documentation
BeautifulSoup:
用于解析HTML/XML文档,提取和操纵网页数据,常用于网页抓取。
re(正则表达式库):
提供正则表达式支持,用于字符串匹配、搜索和替换,适合数据清洗和验证。
urllib:
处理URL和从网络获取数据,包括打开URL、处理异常和解析URLs,便于网页数据抓取。
xlwt:
将数据写入旧版Excel文件(.xls),提供创建工作簿、工作表和写入数据的API。
Flask:
轻量级Web应用框架,使用WSGI,提供路由和模板引擎,适合快速开发Web应用。
jieba:
中文分词库,将中文文本切分为词语,是生成词云前的重要步骤。
matplotlib:
绘图库,提供丰富的绘图功能,用于显示或保存生成的图表,如词云图。
wordcloud:
生成词云的库,词云中词语大小表示其在文本中的出现频率,用于文本可视化。
PIL (Pillow):
图像处理库,用于打开、操作和保存多种格式图像,常用于生成词云时的遮罩图片处理。
numpy:
数学函数库,提供大型多维数组和矩阵运算支持,常用于图像处理(如转换为数组)和数据分析。
sqlite3:
SQLite数据库接口库,提供轻量级、嵌入式的关系型数据库管理功能,用于数据检索和存储。
第一个项目douban(纯python项目):爬取数据并保存到xls和数据库
spider.py
# -*- coding = utf-8 -*-
from bs4 import BeautifulSoup
import re
import urllib.request, urllib.error, urllib.parse
import xlwt
import sqlite3
def main():
baseurl = 'https://movie.douban.com/top250?start='
# 1、爬取网页
datalist = getData(baseurl)
savepath1 = "./豆瓣电影Top250.xls"
saveData(datalist,savepath1)
savepath2 = "./豆瓣电影Top250.db"
initDB(savepath2)
saveData2DB(datalist,savepath2)
# 影片链接的匹配规则
findLink = re.compile(r'<a href="(.*?)">') # 匹配规则的正则表达式对象
# 影片图片
findImg = re.compile(r'<img.*src="(.*?)"', re.S) #re.S忽略换行符
# 影片片名
findTitle = re.compile(r'<span class="title">(.*)</span>')
# 影片的评分
findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
# 影片评价人数
findJudge = re.compile(r'<span>(\d*)人评价</span>', re.S)
# 影片的概况
findInq = re.compile(r'<span class="inq">(.*)</span>')
# 影片的相关内容
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)
def getData(baseurl):
datalist = []
num = 0
# 2、逐一解析数据
for i in range(0, 25): # 调用获取页面信息的函数 10次
url = baseurl + str(i*25)
html = askURL(url) # 保存获取到的单个页面的网页源码
# html = urllib.request.urlopen(url).read()
# 逐一解析数据
soup = BeautifulSoup(html, 'html.parser')
for item in soup.find_all("div", class_="item"):# 定位获取所需的标签内容
# print(item) # 测试:单个电影item
data = []
item = str(item)
link = re.findall(findLink, item)[0].replace('\xa0', "") # \xa0(不间断空白符)
data.append(link)
imgSrc = re.findall(findImg, item)[0].replace('\xa0', "")
data.append(imgSrc)
title = re.findall(findTitle, item)
if(len(title) >= 2):
ctitle = title[0].replace('\xa0', "")
data.append(ctitle)
ftitle = title[1].replace('/',"").replace('\xa0', "")
data.append(ftitle)
elif(len(title) == 1):
data.append(title[0].replace('\xa0', ""))
data.append(" ") # 第二个名称留空
rating = re.findall(findRating, item)[0].replace('\xa0', "")
data.append(rating)
judge = re.findall(findJudge, item)[0].replace('\xa0', "")
data.append(judge)
inq = re.findall(findInq, item)
if len(inq) != 0:
inq = inq[0].replace('。',"").replace('\xa0', "")
data.append(inq)
else:
data.append(" ")
bd = re.findall(findBd, item)[0].replace('\xa0', "")
bd = re.sub(r'<br(\s+)?/>(\s+)?', " ", bd)
bd = re.sub('/', ' ', bd)
data.append(bd.strip())
if data:
num +=1
datalist.append(data)
print(datalist)
print(num)
return datalist
# 得到指定一个URL的网页内容
def askURL(url):
# 模拟浏览器头部信息
head = { # 这里访问的是www.douban.com,加上cookie才成功访问,不然会403
"cookie":'''bid=lmDVVK_MwCE; dbcl2="287312225:gaIljLl3paE"; ck=A87B; _pk_ref.100001.4cf6=%5B%22%22%2C%22%22%2C1740403496%2C%22https%3A%2F%2Faccounts.douban.com%2F%22%5D; _pk_id.100001.4cf6=c5aee2ffb5a4b0b1.1740403496.; push_noty_num=0; push_doumail_num=0; __yadk_uid=FMUehx3EWLsxQlgs8OU0iEQf5rgnlRfM''',
"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0" }
# 用户代理: 表示告诉浏览器我们是什么类型的机器、浏览器(我们能接受什么信息)
req = urllib.request.Request(url, headers=head)
html = ""
try:
response = urllib.request.urlopen(req)
html = response.read().decode("utf-8")
# print(html)
except urllib.error.URLError as e:
if hasattr(e, 'code'): # hasattr 含有指定变量与否
print(e.code)
if hasattr(e, 'reason'):
print(e.reason)
return html
def saveData(datalist,savepath):
print("save...")
book = xlwt.Workbook(encoding='utf-8', style_compression = 0)
sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True)
col = ("电影详情链接", "图片链接", "影片中文名", "影片外国名", "评分", "评价数", "概括", "相关信息")
for i in range(0, 8):
sheet.write(0, i, col[i])
for i in range(0,250):
print("第%d条"%(i+1))
data = datalist[i]
for j in range(0,8):
sheet.write(i+1, j, data[j])
book.save(savepath)
def saveData2DB(datalist,savepath):
conn = sqlite3.connect(savepath)
c = conn.cursor()
print("豆瓣电影-------------------------------------------",len(datalist))
for data in datalist:
for i in range(len(data)):
if i == 4 or i == 5:
pass
else:
data[i] = '"'+str(data[i])+'"'
sql = '''
insert into movie250 (info_link,pic_link,cname,fname,score,rated,instroduction,relax_info)
values (%s)'''%",".join(data)
print(sql)
c.execute(sql)
conn.commit()
conn.close()
print("成功保存到数据库")
def initDB(dbpath):
sql = '''
create table if not exists movie250 (
id integer primary key autoincrement,
info_link text,
pic_link text,
cname varchar,
fname varchar,
score numeric,
rated numeric,
instroduction text,
relax_info text
)
'''
conn = sqlite3.connect(dbpath)
c = conn.cursor()
c.execute(sql)
conn.commit()
conn.close()
if __name__ == '__main__':
main()
第二个项目douban_flask(flask项目):把第一个项目得到的数据库文件的数据可视化
这里只给出python文件,其他文件看教程视频自行下载或看上传的资源又或者GitHub - chenzanhong/Douban_DataVis: 把项目douban获取到的数据(movie.db)可视化:
app.py:
from flask import Flask,render_template
import sqlite3
app = Flask(__name__)
@app.route('/')
def index(): # put application's code here
return render_template('index.html')
@app.route('/index')
def home(): # put application's code here
return render_template('index.html')
# return index() # 请求转发
@app.route('/movie')
def movie(): # put application's code here
datalist = []
conn = sqlite3.connect('豆瓣电影Top250.db')
c = conn.cursor()
sql = '''select * from movie250'''
data = c.execute(sql)
for item in data:
datalist.append(item)
c.close()
conn.close()
return render_template('movie.html', movies=datalist)
@app.route('/score')
def score(): # put application's code here
score = [] # 评分
num = [] # 每个评分的电影数
conn = sqlite3.connect('豆瓣电影Top250.db')
c = conn.cursor()
sql = '''select score,count(score) from movie250 group by score'''
data = c.execute(sql)
for item in data:
score.append(item[0])
num.append(item[1])
c.close()
conn.close()
return render_template('score.html', score=score, num=num)
@app.route('/word')
def word(): # put application's code here
return render_template('word.html')
@app.route('/team')
def team(): # put application's code here
return render_template('team.html')
if __name__ == '__main__':
app.run()
test_WordCloud.py:
import jieba # 分词
# 设置 Matplotlib 后端(如果需要)
import matplotlib
matplotlib.use('TkAgg') # 或者 'Agg', 'Qt5Agg', 等,取决于你的系统支持
from matplotlib import pyplot as plt # 绘图,数据可视化
from wordcloud import WordCloud # 词云
from PIL import Image # 图片处理
import numpy as np # 矩阵运算
import sqlite3 # 数据库
# 准备词云所需的句子
conn = sqlite3.connect('豆瓣电影Top250.db')
c = conn.cursor()
sql = '''select instroduction from movie250'''
data = c.execute(sql)
text = ""
for item in data:
text += item[0]
# print(item[0])
print(text)
c.close()
conn.close()
# 分词
cut = jieba.cut(text)
str = ' '.join(cut)
print(len(str))
# 准备
img = Image.open(r'static\assets\img\b.jpg') # 打开遮罩图片
img_array = np.array(img) # 将图片转换为数据
wc = WordCloud(
background_color = 'white',
mask = img_array,
font_path = r"C:\Windows\Fonts\STXINWEI.TTF", # 改为自己电脑下的路径
scale = 4, # 缩放
# width
# height
)
wc.generate_from_text(str)
# 绘制图片
fig = plt.figure(1)
plt.imshow(wc)
plt.axis('off') # 是否显示坐标轴
# plt.show() # 显示生成的图片
plt.savefig(r'static\assets\img\b2wc.jpg',dpi=500) # dpi为清晰度,可选
效果: