python爬虫,pymongo,pyecharts的使用——原创案例
爬取豆瓣世界高分电影TOP250相关信息,进行数据清洗并存入mongodb数据库,以及读取数据并使用pyecharts进行可视化
一、关键模组的准备
1.安装与mongodb数据库连接的驱动
pip install pymongo
2.安装可视化工具,这里我使用的是pyecharts
pip install pyecharts
二、数据爬取、数据清洗、pymongo数据入库
主要过程:
- 这里我使用自制爬虫,爬取了豆瓣世界TOP250高分电影的相关信息
- 使用BeautifulSoup结合正则表达式、sub、replace等方法进行数据清洗操作,转化为我们想要得到的数据格式
- 创建名为movie的数据库,在其下创建名为dbtop250的集合,将清洗好的数据通过pymongo方法入库
from bs4 import BeautifulSoup # 网页解析,获取数据
import re # 正则表达式,进行文字匹配`
import urllib.request, urllib.error # 制定URL,获取网页数据
from pymongo import MongoClient
findLink = re.compile(r'<a href="(.*?)">') # 创建正则表达式对象,标售规则 影片详情链接的规则
findImgSrc = re.compile(r'<img.*src="(.*?)"', 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>')
findInq = re.compile(r'<span class="inq">(.*)</span>')
findBd = re.compile(r'<p class="">(.*?)</p>', re.S)
def main():
baseurl = "https://movie.douban.com/top250?start=" #要爬取的网页链接
data_get_in(baseurl)
# 爬取网页+数据清洗+数据入库
def data_get_in(baseurl):
client = MongoClient('localhost', 27017)
db = client.movie
order = db.dbtop250
for i in range(0, 10): # 调用获取页面信息的函数,10次
url = baseurl + str(i * 25)
html = askURL(url) # 保存获取到的网页源码
# 2.逐一解析数据
soup = BeautifulSoup(html, "html.parser")
for item in soup.find_all('div', class_="item"): # 查找符合要求的字符串
data = {} # 保存一部电影所有信息
item = str(item)
# print(item)
link = re.findall(findLink, item)[0] # 通过正则表达式查找
data["link"]=link
imgSrc = re.findall(findImgSrc, item)[0]
data["imgsrc"]=imgSrc
titles = re.findall(findTitle, item) #电影名称 中文名称 原名
if (len(titles) == 2):
ctitle = titles[0]
data["ctitle"]=ctitle
otitle = titles[1].replace("\xa0", "") # 消除转义字符
otitle = otitle.replace("/","")
data["title"]=otitle
else:
data["ctitle"] = titles[0]
data["title"] = ' '
rating = re.findall(findRating, item)[0] #评分
data["rating"]=rating
judgeNum = re.findall(findJudge, item)[0] #评论数
data["judgenum"]=judgeNum
inq = re.findall(findInq, item) #介绍语
if len(inq) != 0:
inq = inq[0].replace("。", "")
data["theme"]=inq
else:
data["theme"]=' '
bd = re.findall(findBd, item)[0]
bd = re.sub('<br(\s+)?/>(\s+)?', "!", bd)
bd=bd.strip()
bd=bd.replace("\xa0", " ")
bd=bd.split("!")
data["crew"]=bd[0] #演职表
a=bd[1].split("/")
data["time"]=a[0].strip() #上映时间
data["zone"]=a[1].strip() #上映地区
data["type"]=a[2].strip() #电影类型
print(data)
order.insert_one(data)
# 得到指定一个URL的网页内容
def askURL(url):
head = { # 模拟浏览器头部信息,向豆瓣服务器发送消息
"User-Agent": "Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 80.0.3987.122 Safari / 537.36"
}
# 用户代理,表示告诉豆瓣服务器,我们是什么类型的机器、浏览器(本质上是告诉浏览器,我们可以接收什么水平的文件内容)
request = urllib.request.Request(url, headers=head)
html = ""
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
except urllib.error.URLError as e:
if hasattr(e, "code"):
print(e.code)
if hasattr(e, "reason"):
print(e.reason)
return html
if __name__ == "__main__": # 当程序执行时
main()
print("爬取完毕!")
成功入库!
三、pymongo数据读取、pyecharts数据可视化
1.豆瓣高分电影高产地区TOP10
通过数据处理方法,统计榜单前250电影各个国家地区占有量,并对结果进行数据可视化
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.movie
order = db.dbtop250
data=order.find()
total={}
for a in data: #算法模仿mapreduce词频统计操作,统计榜单前250电影各个国家地区占有量
# print(a["zone"])
x=a["zone"]
x=x.split(" ")
# print(x)
for y in x:
if y in total.keys():
total[y]+=1
else:
total[y]=1
# print(total[y])
total=sorted(total.items(), key=lambda item:item[1],reverse=True)
print(total)
names=[]
plays=[]
for k in total[:10]:
names.append(k[0])
plays.append(k[1])
print(names)
print(plays)
from pyecharts.charts import Bar
from pyecharts import options as opts
bar = (
Bar()
.add_xaxis(names)
.add_yaxis("地区", plays)
.set_global_opts(title_opts=opts.TitleOpts(title="豆瓣高分电影高产地区TOP10", subtitle="TOP250电影地区占有量(部)"))
)
bar.render('豆瓣高分电影高产地区TOP10.html')
2.豆瓣高分电影评论数TOP10
通过数据处理方法,得出世界高分电影TOP250中评论量TOP10的电影,并对结果进行数据可视化
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.movie
order = db.dbtop250
data=order.find()
total={}
for a in data:
x=a["judgenum"]
y=a["ctitle"]
total[y]=x
total=sorted(total.items(), key=lambda item:item[1],reverse=True)
names=[]
plays=[]
for k in total[:10]:
names.append(k[0])
plays.append(k[1])
print(names)
print(plays)
from pyecharts.charts import Bar
from pyecharts import options as opts
bar = (
Bar()
.add_xaxis(names)
.add_yaxis("电影名", plays)
.set_global_opts(title_opts=opts.TitleOpts(title="豆瓣高分电影评论量TOP10", subtitle="TOP250电影评论数(条)")
, xaxis_opts=opts.AxisOpts(name="",axislabel_opts={"rotate":45})
)
)
bar.render('豆瓣高分电影评论量TOP10.html')
如果觉得文章有所价值,点个小赞赞叭O(∩_∩)O