当当网Top500书籍信息爬取与分析

爬取当当网的Top500书籍信息,并对书籍的评价数量进行排序,然后绘制前十名的条形图,然后对各个出版社出版的书籍数量进行排序,绘制百分比的饼图

python 复制代码
# 导入所需的模块
import re  # 正则表达式模块,用于提取文本中的特定模式
from time import sleep  # 用于在循环中添加延迟,避免请求过于频繁
import csv  # 用于读写CSV文件
import requests  # 用于发送HTTP请求,获取网页内容
import pandas as pd  # 用于数据处理和分析
import matplotlib.pyplot as plt  # 用于绘制图表
import numpy as np  # 用于数值计算

# 设置请求头,模拟浏览器访问,避免被网站识别为爬虫
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'
}

# 定义函数,从网页获取特定页面的内容,并以列表形式返回
def getInfo(page):
    page = str(page)  # 将页码转换为字符串
    # 构造目标网页的URL,这里使用了一个无效的网页地址,需要替换成有效的当当网图书排行榜页面URL
    url = '<url id="d0f0ofd96bk4h4b9797g" type="url" status="parsed" title="对不起,您要访问的页面暂时没有找到。" wc="658">http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-24hours-0-0-1-</url> ' + page
    # 发送GET请求,获取网页内容
    response = requests.get(url=url, headers=headers).text
    # 使用正则表达式提取网页中的<li>标签内容
    ex = '(?<=<li>\\s)[\\w\\W]*?(?=</li>)'
    p = re.findall(ex, response)  # 在网页内容中查找所有匹配的模式
    del p[0:3]  # 删除前三个无用的元素(假设前三个元素不是书籍信息)
    return p  # 返回提取到的书籍信息列表

# 定义函数,从字符串中提取书籍的序号
def getIndex(str):
    ex = 'list_num.*?>(.*?)<'  # 匹配序号的正则表达式
    p = re.findall(ex, str)
    return p[0]  # 返回提取到的序号

# 定义函数,从字符串中提取书籍的名称
def getName(str):
    ex = 'title="(.*?)"\\/'  # 匹配书名的正则表达式
    p = re.findall(ex, str)
    return p[0]  # 返回提取到的书名

# 定义函数,从字符串中提取书籍的评论数量
def getCommentCount(str):
    ex = '_blank">([\d]+.*?)<'  # 匹配评论数量的正则表达式
    p = re.findall(ex, str)
    return p[0]  # 返回提取到的评论数量

# 定义函数,从字符串中提取书籍的作者
def getWriter(str):
    ex = 'title="(.*?)"'  # 匹配作者的正则表达式
    p = re.findall(ex, str)
    try:
        return p[2]  # 尝试返回第三个匹配结果(假设作者信息是第三个匹配项)
    except:
        return "暂未找到"  # 如果匹配失败,返回默认值

# 定义函数,从字符串中提取书籍的出版时间
def getTime(str):
    ex = '<span>(.*?)<'  # 匹配出版时间的正则表达式
    p = re.findall(ex, str)
    return p[0]  # 返回提取到的出版时间

# 定义函数,从字符串中提取书籍的出版社
def getPub(str):
    ex = 'key=(.*?)"'  # 匹配出版社的正则表达式
    p = re.findall(ex, str)
    return p[-1]  # 返回最后一个匹配结果(假设出版社信息是最后一个匹配项)

# 定义函数,从字符串中提取书籍的原价
def getPriceFir(str):
    ex = 'price_r">.*?;(.*)<'  # 匹配原价的正则表达式
    p = re.findall(ex, str)
    return p[0]  # 返回提取到的原价

# 定义函数,从字符串中提取书籍的促销价格
def getPriceNow(str):
    ex = 'price_n">.*?;(.*)<'  # 匹配促销价的正则表达式
    p = re.findall(ex, str)
    return p[0]  # 返回提取到的促销价

# 定义主函数,用于爬取多页数据并保存到CSV文件
def main():
    for page in range(1, 26):  # 循环遍历1到25页
        book_list = getInfo(page)  # 获取当前页的书籍列表
        with open('book.csv', 'a', encoding='UTF-8', newline='') as f:  # 打开或创建CSV文件,追加模式
            writer = csv.writer(f)  # 创建CSV写入对象
            # 如果文件是新建的(指针位置为0),则写入表头
            if f.tell() == 0:
                writer.writerow(["序号", "书名", "作者", "出版时间", "出版社", "原价", "促销价","评价量"])
            for info in book_list:  # 遍历每本书的信息
                index = getIndex(info)  # 提取序号
                name = getName(info)  # 提取书名
                priceFir = getPriceFir(info)  # 提取原价
                priceNow = getPriceNow(info)  # 提取促销价
                try:
                    # 提取评论数量,并移除"条评论"字样
                    commentCount = getCommentCount(info).replace("条评论", "")
                except Exception as e:
                    commentCount = 0  # 如果提取失败,设置默认值为0
                writer_name = getWriter(info)  # 提取作者
                pub_time = getTime(info)  # 提取出版时间
                pub = getPub(info)  # 提取出版社
                # 将提取到的信息写入CSV文件
                writer.writerow([index, name, writer_name, pub_time, pub, priceFir, priceNow, commentCount])
        sleep(0.5)  # 每次请求后暂停0.5秒,避免请求过于频繁

# 执行主函数,开始爬取数据
main()

# 读取保存的CSV文件,准备数据分析和可视化
df = pd.read_csv('book.csv', encoding='utf-8')

# 按评价数量降序排序,并取前十名书籍
top_books = df.sort_values(by='评价量', ascending=False).head(10)

# 处理书名,使其每20个字符换一行,便于在图表中显示
top_books['书名'] = top_books['书名'].apply(lambda x: '\n'.join([x[i:i+20] for i in range(0, len(x), 20)]))

# 设置字体,确保正确显示中文和负号
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False

# 创建一个新的图形,设置大小为12x8英寸
plt.figure(figsize=(12, 8))

# 绘制评价数量前十名的书籍的水平条形图
bars = plt.barh(top_books['书名'], top_books['评价量'], color='skyblue')

# 为每个条形添加数据标签
for bar in bars:
    width = bar.get_width()
    plt.text(width - 210000, bar.get_y() + bar.get_height()/2, f'{int(width):,}', va='center')

# 再次绘制条形图以确保标签正确显示
plt.barh(top_books['书名'], top_books['评价量'], color='skyblue')

# 添加坐标轴标签和图表标题
plt.xlabel('评价数量')
plt.title('评价数量前十名的书籍')

# 反转Y轴,使评价最多的书籍显示在顶部
plt.gca().invert_yaxis()

# 调整布局,确保所有元素都能正确显示
plt.tight_layout()

# 显示图表
plt.show()

# 统计各出版社出版的书籍数量
publisher_counts = df['出版社'].value_counts()

# 将数量小于等于2的出版社和空白出版社归类为"其他"
threshold = 3
other = publisher_counts[publisher_counts <= threshold].sum() + publisher_counts.get('', 0)
publisher_counts = publisher_counts[publisher_counts > threshold]
publisher_counts = publisher_counts.drop('', errors='ignore')  # 删除空白出版社
publisher_counts['其他'] = other  # 添加"其他"类别

# 绘制出版社百分比饼图
plt.figure(figsize=(10, 10))
patches, texts, autotexts = plt.pie(publisher_counts, autopct='%1.1f%%', startangle=140)

# 添加图例
plt.legend(patches, publisher_counts.index, loc='lower center', bbox_to_anchor=(0.5, -0.2), ncol=5)

# 添加图表标题
plt.title('各出版社出版书籍数量百分比')

# 调整布局并显示图表
plt.tight_layout()
plt.show()
相关推荐
橙色小博5 分钟前
Python中的re库详细用法与代码解析
linux·python·正则表达式·php·re
满怀101512 分钟前
【库(Library)、包(Package)和模块(Module)解析】
python
zhojiew25 分钟前
learning ray之ray强化学习/超参调优和数据处理
python·ai
bryant_meng37 分钟前
【python】Calculate the Angle of a Triangle
开发语言·python·算法
未来之窗软件服务1 小时前
1k实现全磁盘扫描搜索——仙盟创梦IDE-智能编程 编程工具设计
ide·python·仙盟创梦ide
小白学大数据1 小时前
Python爬虫+代理IP+Header伪装:高效采集亚马逊数据
爬虫·python·tcp/ip·scrapy
测试开发Kevin1 小时前
以pytest_addoption 为例,讲解pytest框架中钩子函数的应用
python·pytest
仙人掌_lz1 小时前
从零开始理解FlashAttention:算法细节图解
人工智能·python·深度学习·算法·ai·flashattention
PixelMind2 小时前
【LUT技术专题】ECLUT代码解读
开发语言·python·深度学习·图像超分辨率
TravelLight922 小时前
Python pandas 向excel追加数据,不覆盖之前的数据
python·excel·pandas