python之爬取豆瓣排行与可视化

 找到目标网址:

url = "https://movie.douban.com/chart"
豆瓣电影排行榜

鼠标右键,检查 复制url,与user-agent:

 

url = "https://movie.douban.com/chart"
headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"
}

 鼠标右键+查看源代码,找到电影目标位置

 

 匹配正则表达式

# 匹配
obj = re.compile(r'<div class="pl2">.*?<a .*?>(?P<name>.*?)</a>.*?'
                 r'<div class="star clearfix">.*?<span class="rating_nums">(?P<score>.*?)</span>.*?'
                 r'<span class="pl">\((?P<total>.*?)人评价\)</span>', re.S)

 可视化参考:

python爬取B站弹幕评论-CSDN博客

python之搞定Matplotlib从入门到实战演练-CSDN博客

完整代码:

import requests
import re
import matplotlib.pyplot as plt
import numpy as np

url = "https://movie.douban.com/chart"
headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0"
}

resp = requests.get(url, headers=headers)
page_content = resp.text

# 匹配
obj = re.compile(r'<div class="pl2">.*?<a .*?>(?P<name>.*?)</a>.*?'
                 r'<div class="star clearfix">.*?<span class="rating_nums">(?P<score>.*?)</span>.*?'
                 r'<span class="pl">\((?P<total>.*?)人评价\)</span>', re.S)
# 存储电影数据的列表
movies = []
# 开始匹配
result = obj.finditer(page_content)
for it in result:
    # strip()方法:去除提取出的电影名称两端的空白字符
    # replace()方法:去除斜杠及其后面的内容
    name = it.group("name").strip().split('/')[0]
    score = it.group("score")
    total = it.group("total")
    # 为每部电影创建一个字典
    movie_info = {
        "电影名称": name.strip(),
        "电影评分": score,
        "评价人数": total
    }
    movies.append(movie_info)

    # print(f"电影名称:{name.strip()}\n电影评分:{score}\n评价人数:{total}\n")

    # 打印电影字典列表
for movie in movies:
    print(movie)

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']  # 显示中文标签

# 提取数据用于绘图
movie_names = [movie["电影名称"] for movie in movies]
movie_scores = [float(movie["电影评分"]) for movie in movies]
movie_totals = [int(movie["评价人数"].replace(',', '')) for movie in movies]

# 创建柱状图
# 设置图形的大小。它是一个元组,包含两个数字,分别表示图形的宽度和高度
# fig, (ax1, ax2)创建一个图形和两个子图,子图排列为一行两列
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 7))  # 创建一个包含两个子图的图形

# 第一个子图:电影评分
x = np.arange(len(movie_names))
width = 0.35
# rects1是一个BarContainer对象
rects1 = ax1.bar(x - width / 2, movie_scores, width, label='电影评分', color='blue', alpha=0.7)

# 每个柱顶标上数量
for bar in rects1:
    height = bar.get_height()  # 获取条形的高度
    x_pos = bar.get_x() + width / 2  # 计算 x 坐标,使标签居中于条形
    y_pos = height + 0.1  # 计算 y 坐标,稍微高于条形顶部以避免重叠(0.1 是个调整值,可以根据需要修改)
    ax1.text(x_pos, y_pos, f'{height}', ha='center', va='bottom')  # 在条形上方添加标签

ax1.set_xticks(x)
ax1.set_xticklabels(movie_names, rotation=-45, ha='left')
ax1.set_title('电影评分')
ax1.set_xlabel('电影名称')
ax1.set_ylabel('评分')
ax1.legend()
ax1.grid(axis='y', linestyle='--', alpha=0.7)

# 第二个子图:评价人数
rects2 = ax2.bar(x + width / 2, movie_totals, width, label='评价人数', color='green', alpha=0.7)

# 每个柱顶标上数量
for bar in rects2:
    height = bar.get_height()  # 获取条形的高度
    x_pos = bar.get_x() + width / 2  # 计算 x 坐标,使标签居中于条形
    y_pos = height + 0.1  # 计算 y 坐标,稍微高于条形顶部以避免重叠(0.1 是个调整值,可以根据需要修改)
    ax2.text(x_pos, y_pos, f'{height}', ha='center', va='bottom')  # 在条形上方添加标签

ax2.set_xticks(x)
ax2.set_xticklabels(movie_names, rotation=-45, ha='left')
ax2.set_title('评价人数')
ax2.set_xlabel('电影名称')
ax2.set_ylabel('人数')
ax2.legend()
ax2.grid(axis='y', linestyle='--', alpha=0.7)

# 调整布局以避免重叠
fig.tight_layout()

# 显示图形
plt.show()

恭喜您学会了,快去试试吧 !!!

猜你喜欢

转载自blog.csdn.net/weixin_51891232/article/details/143171127