如何用Python编写示例代码爬取并展示电影票房数据图表?
- 内容介绍
- 文章标签
- 相关推荐
本文共计857个文字,预计阅读时间需要4分钟。
本实例演示了如何使用Python爬虫获取电影票房数据及图表展示。以下是一个简单的爬虫操作步骤:
1. 使用Python的requests库发送HTTP请求,获取网页内容。
2.使用BeautifulSoup解析网页内容,提取电影票房排行榜信息。
3.将提取的数据存储到文件或数据库中。
4.使用matplotlib库将数据可视化,生成图表。
以下是一个示例代码:
python
import requestsfrom bs4 import BeautifulSoupimport matplotlib.pyplot as plt发送HTTP请求获取网页内容url='http://www.cbooo.cn/BoxOffice/getInlandpIndex=1t=0'response=requests.get(url)
使用BeautifulSoup解析网页内容soup=BeautifulSoup(response.text, '.parser')提取电影票房排行榜信息table=soup.find('table', {'class': 'chart'})rows=table.find_all('tr')
提取数据data=[]for row in rows[1:]: # 跳过行 cols=row.find_all('td') data.append([col.text for col in cols])
存储数据到文件with open('movie_box_office.txt', 'w', encoding='utf-8') as f: for item in data: f.write(','.join(item) + '\n')
可视化数据movies=[item[1] for item in data]box_office=[int(item[2].replace('亿', '')) for item in data]
plt.figure(figsize=(10, 5))plt.bar(movies, box_office)plt.xlabel('电影')plt.ylabel('票房(亿)')plt.title('电影票房排行榜')plt.xticks(rotation=45)plt.tight_layout()plt.show()
这段代码实现了爬取电影票房排行榜数据,并将其存储到文件中,同时使用matplotlib库生成柱状图进行可视化展示。
本文实例讲述了Python爬虫爬取电影票房数据及图表展示操作。分享给大家供大家参考,具体如下:
爬虫电影历史票房排行榜 www.cbooo.cn/BoxOffice/getInland?pIndex=1&t=0
- Python爬取历史电影票房纪录
- 解析Json数据
- 横向条形图展示
- 面向对象思想
导入相关库
import requests import re from matplotlib import pyplot as plt from matplotlib import font_manager import json
类代码部分
class DYOrder(object): #初始化 def __init__(self,page=1): self.url = 'www.cbooo.cn/BoxOffice/getInland?pIndex={}&t=0'.format(page) self.headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'} #请求 def __to_request(self): response = requests.get(url=self.url,headers=self.headers) return self.__to_parse(response.content.decode('utf-8')) #解析 def __to_parse(self,html): #返回为JSON字符串 #首先将字符串反序列化为JSON对象 my_json = json.loads(html) return my_json #图表展示 def __to_show(self,data,show_type): x = [] y = [] for value in data: x.append(value['MovieName']) y.append(int(value['BoxOffice'])) my_font = font_manager.FontProperties(fname='/System/Library/Fonts/PingFang.ttc',size=18) if show_type == 1: plt.figure(figsize=(20,8),dpi=80) rects = plt.bar(range(len(x)),[float(i) for i in y],width=0.5,color='red') plt.xticks(range(len(x)),x,fontproperties=my_font,rotation=60) plt.xlabel('名称',rotation=60,color='blue',fontproperties=my_font) plt.ylabel('票房/万',rotation=60,color='blue',fontproperties=my_font) for rect in rects: height = rect.get_height() plt.text(rect.get_x() + rect.get_width()/2,height+0.4,str(height),ha='center',rotation=30) else: # 横向 plt.barh(y,x) plt.figure(figsize=(15,13),dpi=80) rects = plt.barh(range(len(x)),y,height=0.8,color='orange') plt.yticks(range(len(x)),x,fontproperties=my_font,rotation=30) plt.ylabel('名称',rotation=0,color='blue',fontproperties=my_font) plt.xlabel('票房/万',rotation=60,color='blue',fontproperties=my_font) for rect in rects: width = rect.get_width() plt.text(width, rect.get_y()+0.3/2,str(width),va='center',rotation=30) plt.grid(alpha=0.4) plt.title('中国电影历史票房排行榜',color='red',size=18,fontproperties=my_font) plt.show() #所有操作 def to_run(self,show_type=1): result = self.__to_request() self.__to_show(result,show_type)
调用类并展示
if __name__ == '__main__': dy_order = DYOrder(1) # type 1 竖向条形图 2 横向 dy_order.to_run(2)
更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
本文共计857个文字,预计阅读时间需要4分钟。
本实例演示了如何使用Python爬虫获取电影票房数据及图表展示。以下是一个简单的爬虫操作步骤:
1. 使用Python的requests库发送HTTP请求,获取网页内容。
2.使用BeautifulSoup解析网页内容,提取电影票房排行榜信息。
3.将提取的数据存储到文件或数据库中。
4.使用matplotlib库将数据可视化,生成图表。
以下是一个示例代码:
python
import requestsfrom bs4 import BeautifulSoupimport matplotlib.pyplot as plt发送HTTP请求获取网页内容url='http://www.cbooo.cn/BoxOffice/getInlandpIndex=1t=0'response=requests.get(url)
使用BeautifulSoup解析网页内容soup=BeautifulSoup(response.text, '.parser')提取电影票房排行榜信息table=soup.find('table', {'class': 'chart'})rows=table.find_all('tr')
提取数据data=[]for row in rows[1:]: # 跳过行 cols=row.find_all('td') data.append([col.text for col in cols])
存储数据到文件with open('movie_box_office.txt', 'w', encoding='utf-8') as f: for item in data: f.write(','.join(item) + '\n')
可视化数据movies=[item[1] for item in data]box_office=[int(item[2].replace('亿', '')) for item in data]
plt.figure(figsize=(10, 5))plt.bar(movies, box_office)plt.xlabel('电影')plt.ylabel('票房(亿)')plt.title('电影票房排行榜')plt.xticks(rotation=45)plt.tight_layout()plt.show()
这段代码实现了爬取电影票房排行榜数据,并将其存储到文件中,同时使用matplotlib库生成柱状图进行可视化展示。
本文实例讲述了Python爬虫爬取电影票房数据及图表展示操作。分享给大家供大家参考,具体如下:
爬虫电影历史票房排行榜 www.cbooo.cn/BoxOffice/getInland?pIndex=1&t=0
- Python爬取历史电影票房纪录
- 解析Json数据
- 横向条形图展示
- 面向对象思想
导入相关库
import requests import re from matplotlib import pyplot as plt from matplotlib import font_manager import json
类代码部分
class DYOrder(object): #初始化 def __init__(self,page=1): self.url = 'www.cbooo.cn/BoxOffice/getInland?pIndex={}&t=0'.format(page) self.headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'} #请求 def __to_request(self): response = requests.get(url=self.url,headers=self.headers) return self.__to_parse(response.content.decode('utf-8')) #解析 def __to_parse(self,html): #返回为JSON字符串 #首先将字符串反序列化为JSON对象 my_json = json.loads(html) return my_json #图表展示 def __to_show(self,data,show_type): x = [] y = [] for value in data: x.append(value['MovieName']) y.append(int(value['BoxOffice'])) my_font = font_manager.FontProperties(fname='/System/Library/Fonts/PingFang.ttc',size=18) if show_type == 1: plt.figure(figsize=(20,8),dpi=80) rects = plt.bar(range(len(x)),[float(i) for i in y],width=0.5,color='red') plt.xticks(range(len(x)),x,fontproperties=my_font,rotation=60) plt.xlabel('名称',rotation=60,color='blue',fontproperties=my_font) plt.ylabel('票房/万',rotation=60,color='blue',fontproperties=my_font) for rect in rects: height = rect.get_height() plt.text(rect.get_x() + rect.get_width()/2,height+0.4,str(height),ha='center',rotation=30) else: # 横向 plt.barh(y,x) plt.figure(figsize=(15,13),dpi=80) rects = plt.barh(range(len(x)),y,height=0.8,color='orange') plt.yticks(range(len(x)),x,fontproperties=my_font,rotation=30) plt.ylabel('名称',rotation=0,color='blue',fontproperties=my_font) plt.xlabel('票房/万',rotation=60,color='blue',fontproperties=my_font) for rect in rects: width = rect.get_width() plt.text(width, rect.get_y()+0.3/2,str(width),va='center',rotation=30) plt.grid(alpha=0.4) plt.title('中国电影历史票房排行榜',color='red',size=18,fontproperties=my_font) plt.show() #所有操作 def to_run(self,show_type=1): result = self.__to_request() self.__to_show(result,show_type)
调用类并展示
if __name__ == '__main__': dy_order = DYOrder(1) # type 1 竖向条形图 2 横向 dy_order.to_run(2)
更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。

