哔哩哔哩IT私塾python爬虫视频教程中的项目文件

[复制链接]
发表于 昨天 14:46 | 显示全部楼层 |阅读模式
视频链接:
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
  1. # -*- coding = utf-8 -*-
  2. from bs4 import BeautifulSoup
  3. import re
  4. import urllib.request, urllib.error, urllib.parse
  5. import xlwt
  6. import sqlite3
  7. def main():
  8.     baseurl = 'https://movie.douban.com/top250?start='
  9.     # 1、爬取网页
  10.     datalist = getData(baseurl)
  11.     savepath1 = "./豆瓣电影Top250.xls"
  12.     saveData(datalist,savepath1)
  13.     savepath2 = "./豆瓣电影Top250.db"
  14.     initDB(savepath2)
  15.     saveData2DB(datalist,savepath2)
  16. # 影片链接的匹配规则
  17. findLink = re.compile(r'<a href="(.*?)">')    # 匹配规则的正则表达式对象
  18. # 影片图片
  19. findImg = re.compile(r'<img.*src="(.*?)"', re.S)    #re.S忽略换行符
  20. # 影片片名
  21. findTitle = re.compile(r'<span class="title">(.*)</span>')
  22. # 影片的评分
  23. findRating = re.compile(r'<span class="rating_num" property="v:average">(.*)</span>')
  24. # 影片评价人数
  25. findJudge = re.compile(r'<span>(\d*)人评价</span>', re.S)
  26. # 影片的概况
  27. findInq = re.compile(r'<span class="inq">(.*)</span>')
  28. # 影片的相关内容
  29. findBd = re.compile(r'<p class="">(.*?)</p>', re.S)
  30. def getData(baseurl):
  31.     datalist = []
  32.     num = 0
  33.     # 2、逐一解析数据
  34.     for i in range(0, 25):   # 调用获取页面信息的函数 10次
  35.         url = baseurl + str(i*25)
  36.         html = askURL(url)  # 保存获取到的单个页面的网页源码
  37.         # html = urllib.request.urlopen(url).read()
  38.         # 逐一解析数据
  39.         soup = BeautifulSoup(html, 'html.parser')
  40.         for item in soup.find_all("div", class_="item"):# 定位获取所需的标签内容
  41.             # print(item) # 测试:单个电影item
  42.             data = []
  43.             item = str(item)
  44.             link = re.findall(findLink, item)[0].replace('\xa0', "")    # \xa0(不间断空白符)
  45.             data.append(link)
  46.             imgSrc = re.findall(findImg, item)[0].replace('\xa0', "")
  47.             data.append(imgSrc)
  48.             title = re.findall(findTitle, item)
  49.             if(len(title) >= 2):
  50.                 ctitle = title[0].replace('\xa0', "")
  51.                 data.append(ctitle)
  52.                 ftitle = title[1].replace('/',"").replace('\xa0', "")
  53.                 data.append(ftitle)
  54.             elif(len(title) == 1):
  55.                 data.append(title[0].replace('\xa0', ""))
  56.                 data.append(" ")    # 第二个名称留空
  57.             rating = re.findall(findRating, item)[0].replace('\xa0', "")
  58.             data.append(rating)
  59.             judge = re.findall(findJudge, item)[0].replace('\xa0', "")
  60.             data.append(judge)
  61.             inq = re.findall(findInq, item)
  62.             if len(inq) != 0:
  63.                 inq = inq[0].replace('。',"").replace('\xa0', "")
  64.                 data.append(inq)
  65.             else:
  66.                 data.append(" ")
  67.             bd = re.findall(findBd, item)[0].replace('\xa0', "")
  68.             bd = re.sub(r'<br(\s+)?/>(\s+)?', " ", bd)
  69.             bd = re.sub('/', ' ', bd)
  70.             data.append(bd.strip())
  71.             if data:
  72.                 num +=1
  73.             datalist.append(data)
  74.     print(datalist)
  75.     print(num)
  76.     return datalist
  77. # 得到指定一个URL的网页内容
  78. def askURL(url):
  79.     # 模拟浏览器头部信息
  80.     head = {    # 这里访问的是www.douban.com,加上cookie才成功访问,不然会403
  81.         "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''',
  82.         "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" }
  83.     # 用户代理: 表示告诉浏览器我们是什么类型的机器、浏览器(我们能接受什么信息)
  84.     req = urllib.request.Request(url, headers=head)
  85.     html = ""
  86.     try:
  87.         response = urllib.request.urlopen(req)
  88.         html = response.read().decode("utf-8")
  89.         # print(html)
  90.     except urllib.error.URLError as e:
  91.         if hasattr(e, 'code'):  # hasattr 含有指定变量与否
  92.             print(e.code)
  93.         if hasattr(e, 'reason'):
  94.             print(e.reason)
  95.     return html
  96. def saveData(datalist,savepath):
  97.     print("save...")
  98.     book = xlwt.Workbook(encoding='utf-8', style_compression = 0)
  99.     sheet = book.add_sheet('豆瓣电影Top250', cell_overwrite_ok=True)
  100.     col = ("电影详情链接", "图片链接", "影片中文名", "影片外国名", "评分", "评价数", "概括", "相关信息")
  101.     for i in range(0, 8):
  102.         sheet.write(0, i, col[i])
  103.     for i in range(0,250):
  104.         print("第%d条"%(i+1))
  105.         data = datalist[i]
  106.         for j in range(0,8):
  107.             sheet.write(i+1, j, data[j])
  108.     book.save(savepath)
  109. def saveData2DB(datalist,savepath):
  110.     conn = sqlite3.connect(savepath)
  111.     c = conn.cursor()
  112.     print("豆瓣电影-------------------------------------------",len(datalist))
  113.     for data in datalist:
  114.         for i in range(len(data)):
  115.             if i == 4 or i == 5:
  116.                 pass
  117.             else:
  118.                 data[i] = '"'+str(data[i])+'"'
  119.         sql = '''
  120.             insert into movie250 (info_link,pic_link,cname,fname,score,rated,instroduction,relax_info)
  121.             values (%s)'''%",".join(data)
  122.         print(sql)
  123.         c.execute(sql)
  124.     conn.commit()
  125.     conn.close()
  126.     print("成功保存到数据库")
  127. def initDB(dbpath):
  128.     sql = '''
  129.         create table if not exists movie250 (
  130.             id integer primary key autoincrement,
  131.             info_link text,
  132.             pic_link text,
  133.             cname varchar,
  134.             fname varchar,
  135.             score numeric,
  136.             rated numeric,
  137.             instroduction text,
  138.             relax_info text
  139.         )
  140.     '''
  141.     conn = sqlite3.connect(dbpath)
  142.     c = conn.cursor()
  143.     c.execute(sql)
  144.     conn.commit()
  145.     conn.close()
  146. if __name__ == '__main__':
  147.     main()
复制代码
第二个项目douban_flask(flask项目):把第一个项目得到的数据库文件的数据可视化
这里只给出python文件,其他文件看教程视频自行下载或看上传的资源又大概GitHub - chenzanhong/Douban_DataVis: 把项目douban获取到的数据(movie.db)可视化:
app.py:
  1. from flask import Flask,render_template
  2. import sqlite3
  3. app = Flask(__name__)
  4. @app.route('/')
  5. def index():  # put application's code here
  6.     return render_template('index.html')
  7. @app.route('/index')
  8. def home():  # put application's code here
  9.     return render_template('index.html')
  10.     # return index()    # 请求转发
  11. @app.route('/movie')
  12. def movie():  # put application's code here
  13.     datalist = []
  14.     conn = sqlite3.connect('豆瓣电影Top250.db')
  15.     c = conn.cursor()
  16.     sql = '''select * from movie250'''
  17.     data = c.execute(sql)
  18.     for item in data:
  19.         datalist.append(item)
  20.     c.close()
  21.     conn.close()
  22.     return render_template('movie.html', movies=datalist)
  23. @app.route('/score')
  24. def score():  # put application's code here
  25.     score = []  # 评分
  26.     num = []    # 每个评分的电影数
  27.     conn = sqlite3.connect('豆瓣电影Top250.db')
  28.     c = conn.cursor()
  29.     sql = '''select score,count(score) from movie250 group by score'''
  30.     data = c.execute(sql)
  31.     for item in data:
  32.         score.append(item[0])
  33.         num.append(item[1])
  34.     c.close()
  35.     conn.close()
  36.     return render_template('score.html', score=score, num=num)
  37. @app.route('/word')
  38. def word():  # put application's code here
  39.     return render_template('word.html')
  40. @app.route('/team')
  41. def team():  # put application's code here
  42.     return render_template('team.html')
  43. if __name__ == '__main__':
  44.     app.run()
复制代码
test_WordCloud.py:
  1. import jieba    # 分词
  2. # 设置 Matplotlib 后端(如果需要)
  3. import matplotlib
  4. matplotlib.use('TkAgg')  # 或者 'Agg', 'Qt5Agg', 等,取决于你的系统支持
  5. from matplotlib import pyplot as plt    # 绘图,数据可视化
  6. from wordcloud import WordCloud # 词云
  7. from PIL import Image   # 图片处理
  8. import numpy as np  # 矩阵运算
  9. import sqlite3  # 数据库
  10. # 准备词云所需的句子
  11. conn = sqlite3.connect('豆瓣电影Top250.db')
  12. c = conn.cursor()
  13. sql = '''select instroduction from movie250'''
  14. data = c.execute(sql)
  15. text = ""
  16. for item in data:
  17.     text += item[0]
  18.     # print(item[0])
  19. print(text)
  20. c.close()
  21. conn.close()
  22. # 分词
  23. cut = jieba.cut(text)
  24. str = ' '.join(cut)
  25. print(len(str))
  26. # 准备
  27. img = Image.open(r'static\assets\img\b.jpg') # 打开遮罩图片
  28. img_array = np.array(img)   # 将图片转换为数据
  29. wc = WordCloud(
  30.     background_color = 'white',
  31.     mask = img_array,
  32.     font_path = r"C:\Windows\Fonts\STXINWEI.TTF",    # 改为自己电脑下的路径
  33.     scale = 4,  # 缩放
  34.     # width
  35.     # height
  36. )
  37. wc.generate_from_text(str)
  38. # 绘制图片
  39. fig = plt.figure(1)
  40. plt.imshow(wc)
  41. plt.axis('off') # 是否显示坐标轴
  42. # plt.show()  # 显示生成的图片
  43. plt.savefig(r'static\assets\img\b2wc.jpg',dpi=500)  # dpi为清晰度,可选
复制代码
效果:
 





免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表