• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    利用python抓取HTML页面数据并作可视化数据分析

    发布者: 福建二哥 | 发布时间: 2025-6-14 12:22| 查看数: 137| 评论数: 0|帖子模式

    本文所展示的代码是一个完整的数据采集、处理与可视化工具,主要用于从指定网站下载Excel文件,解析其中的数据,并生成投资者数量的趋势图表。以下是代码的主要功能模块及其作用:

    1.网页数据获取

    使用fetch_html_page函数从目标网站抓取HTML页面内容。
    通过parse_html_for_excel_links解析HTML内容,提取所有Excel文件链接。
    利用parse_html_for_max_page解析最大分页数,确保能够遍历所有页面。

    2.文件下载与存储

    download_excel_file负责根据Excel文件的URL下载文件并保存到本地指定路径。
    download_excel_data实现批量下载功能,支持多页数据的完整采集。

    3.数据读取与处理

    read_excel_file使用pandas库读取Excel文件内容。
    process_excel_data将Excel数据转换为字典格式,便于后续处理。
    process_downloaded_files批量处理下载的Excel文件,提取关键数据并存储为列表。

    4.数据可视化

    plot_investor_trends利用matplotlib绘制双Y轴折线图,展示个人投资者和机构投资者的数量变化趋势。
    图表包含日期、个人投资者数量(万名)和机构投资者数量(家),并通过不同颜色区分数据系列。
    整体流程
    代码从指定网站抓取数据,自动下载相关Excel文件。
    解析Excel文件中的投资者数据,并生成趋势图表以直观展示数据变化。
    1. import warnings

    2. import requests
    3. from bs4 import BeautifulSoup
    4. import pandas as pd
    5. import os
    6. import re
    7. import matplotlib

    8. # 设置matplotlib的字体配置,以支持中文显示
    9. matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 或者 ['Microsoft YaHei']
    10. matplotlib.rcParams['axes.unicode_minus'] = False
    11. matplotlib.use('TkAgg')
    12. from matplotlib import pyplot as plt


    13. def fetch_html_page(url):
    14.     """
    15.     获取HTML页面内容。

    16.     参数:
    17.     url (str): 目标网页的URL。

    18.     返回:
    19.     str: 页面的HTML内容,如果请求失败则返回None。
    20.     """
    21.     headers = {
    22.         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    23.     }
    24.     response = requests.get(url, headers=headers)
    25.     if response.status_code == 200:
    26.         print(f"成功获取页面: {url}")
    27.         return response.text
    28.     else:
    29.         print(f"Error: {response.status_code}, {response.text}")
    30.         return None


    31. def parse_html_for_excel_links(html_content):
    32.     """
    33.     解析HTML内容中的Excel链接。

    34.     参数:
    35.     html_content (str): HTML页面内容。

    36.     返回:
    37.     list: 包含所有找到的Excel文件链接的列表。
    38.     """
    39.     soup = BeautifulSoup(html_content, 'html.parser')
    40.     excel_links = []
    41.     for a_tag in soup.find_all('a', href=True):
    42.         href = a_tag.get('href')
    43.         if href and href.endswith('.xlsx'):
    44.             excel_links.append(href)
    45.     return excel_links


    46. def parse_html_for_max_page(html_content):
    47.     """
    48.     解析HTML内容以找到最大页面数。

    49.     参数:
    50.     html_content (str): HTML页面内容。

    51.     返回:
    52.     int: 最大页面数。
    53.     """
    54.     soup = BeautifulSoup(html_content, 'html.parser')
    55.     max_page = 1
    56.     for a_tag in soup.find_all('a', class_='pagingNormal'):
    57.         onclick = a_tag.get('onclick')
    58.         if onclick:
    59.             match = re.search(r"'(/test/j/[^']+)'", onclick)
    60.             if match:
    61.                 page_number = match.group(1).split('-')[-1].split('.')[0]
    62.                 max_page = max(max_page, int(page_number))
    63.     return max_page


    64. def download_excel_file(url, save_path):
    65.     """
    66.     下载Excel文件并保存到指定路径。

    67.     参数:
    68.     url (str): Excel文件的URL。
    69.     save_path (str): 文件的保存路径。
    70.     """
    71.     headers = {
    72.         "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
    73.     }
    74.     response = requests.get(url, headers=headers)
    75.     if response.status_code == 200:
    76.         with open(save_path, 'wb') as f:
    77.             f.write(response.content)
    78.         print(f"下载完成: {save_path}")
    79.     else:
    80.         print(f"Error: {response.status_code}, {response.text}")


    81. def download_excel_data():
    82.     """
    83.     下载所有Excel数据文件。
    84.     """
    85.     base_url = 'https://test/index.html'  # 替换为实际网页地址
    86.     current_url = base_url
    87.     page_number = 1

    88.     html_content = fetch_html_page(current_url)
    89.     if not html_content:
    90.         return

    91.     max_page = parse_html_for_max_page(html_content)
    92.     print(f"最大页面数: {max_page}")

    93.     while page_number <= max_page:
    94.         print(f"正在处理第 {page_number} 页: {current_url}")
    95.         html_content = fetch_html_page(current_url)
    96.         if not html_content:
    97.             break

    98.         excel_links = parse_html_for_excel_links(html_content)
    99.         if not excel_links:
    100.             print("未找到Excel链接。")
    101.             break

    102.         for link in excel_links:
    103.             full_url = f"https://www.test.cn{link}"
    104.             # 提取日期和文件名部分
    105.             file_path_parts = link.split('/')
    106.             file_name = ('/'.join(file_path_parts[-3:-1]) + '/' + file_path_parts[-1]).replace('/', '-')
    107.             save_path = os.path.join('downloads', file_name)
    108.             os.makedirs(os.path.dirname(save_path), exist_ok=True)
    109.             download_excel_file(full_url, save_path)

    110.         if page_number < max_page:
    111.             next_page_link = f"/test/d2bb5c19-{page_number + 1}.html"
    112.             current_url = f"https://www.test.cn{next_page_link}"
    113.             page_number += 1
    114.         else:
    115.             print("没有更多页面。")
    116.             break


    117. def read_excel_file(file_path):
    118.     """
    119.     读取Excel文件内容。

    120.     参数:
    121.     file_path (str): Excel文件的路径。

    122.     返回:
    123.     DataFrame: 读取到的Excel文件内容,如果读取失败则返回None。
    124.     """
    125.     try:
    126.         with warnings.catch_warnings():
    127.             warnings.simplefilter("ignore", UserWarning)
    128.             df = pd.read_excel(file_path, engine='openpyxl', header=None)
    129.         return df
    130.     except Exception as e:
    131.         print(f"读取Excel文件时出错: {e}")
    132.         return None


    133. def process_excel_data(df):
    134.     """
    135.     处理Excel数据,将其转换为字典格式。

    136.     参数:
    137.     df (DataFrame): Excel文件内容。

    138.     返回:
    139.     dict: 转换后的字典数据。
    140.     """
    141.     if df is None:
    142.         return {}

    143.     # 处理合并单元格
    144.     # df = df.fillna(method='ffill').fillna(method='bfill')

    145.     # 将数据转换为字典
    146.     data_dict = {}
    147.     current_section = None
    148.     for index, row in df.iterrows():
    149.         if index == 1:  # 第二行
    150.             key = row[1]
    151.             if pd.isnull(key):
    152.                 key = df.iloc[1, 0]
    153.             value = row[2] if pd.notnull(row[2]) else None
    154.             data_dict[key] = value
    155.         elif index > 1:
    156.             if pd.notnull(row[0]):
    157.                 current_section = row[0]
    158.                 data_dict[current_section] = {}
    159.             if pd.notnull(row[1]):
    160.                 key = row[1]
    161.                 value = row[2] if pd.notnull(row[2]) else None
    162.                 data_dict[current_section][key] = value

    163.     return data_dict


    164. def process_downloaded_files(directory):
    165.     """
    166.     处理下载的Excel文件,提取数据。

    167.     参数:
    168.     directory (str): 存放下载文件的目录路径。

    169.     返回:
    170.     list: 包含所有处理后的数据字典的列表。
    171.     """
    172.     data_list = []
    173.     for filename in os.listdir(directory):
    174.         if filename.endswith('.xlsx'):
    175.             file_path = os.path.join(directory, filename)
    176.             df = read_excel_file(file_path)
    177.             if df is not None:
    178.                 print(f"处理文件: {filename}")
    179.                 data_dict = process_excel_data(df)
    180.                 print(data_dict)  # 打印处理后的字典
    181.                 data_list.append(data_dict)
    182.     return data_list


    183. def plot_investor_trends(data_list):
    184.     """
    185.     绘制投资者数量趋势图。

    186.     参数:
    187.     data_list (list): 包含投资者数据的列表。
    188.     """
    189.     # 提取时间值和投资者数量
    190.     dates = []
    191.     individual_investors = []
    192.     institutional_investors = []

    193.     for data_dict in data_list:
    194.         date_str = data_dict['统计指标']
    195.         date = pd.to_datetime(date_str)
    196.         dates.append(date)
    197.         individual_investors.append(data_dict['证券公司开展业务情况']['个人投资者数量(万名)'])
    198.         institutional_investors.append(data_dict['证券公司开展业务情况']['机构投资者数量(家)'])

    199.     # 创建折线图
    200.     fig, ax1 = plt.subplots(figsize=(10, 6))

    201.     # 绘制个人投资者数量
    202.     color = 'tab:red'
    203.     ax1.set_xlabel('日期')
    204.     ax1.set_ylabel('个人投资者数量(万名)', color=color)
    205.     ax1.plot(dates, individual_investors, color=color, label='个人投资者数量(万名)', marker='o')
    206.     ax1.tick_params(axis='y', labelcolor=color)

    207.     # 创建第二个 Y 轴
    208.     ax2 = ax1.twinx()  # 共享 X 轴

    209.     # 绘制机构投资者数量
    210.     color = 'tab:blue'
    211.     ax2.set_ylabel('机构投资者数量(家)', color=color)
    212.     ax2.plot(dates, institutional_investors, color=color, label='机构投资者数量(家)', marker='o')
    213.     ax2.tick_params(axis='y', labelcolor=color)

    214.     # 设置标题和图例
    215.     fig.tight_layout()  # 调整子图参数,防止标签重叠
    216.     plt.title('投资者数量趋势')
    217.     fig.legend(loc='upper left', bbox_to_anchor=(0.1, 0.9))

    218.     # 显示图形
    219.     plt.show()


    220. # 调用函数绘制投资者趋势图
    221. plot_investor_trends(process_downloaded_files('downloads'))
    复制代码


    到此这篇关于利用python抓取HTML页面数据并作可视化数据分析的文章就介绍到这了,更多相关python抓取HTML页面数据内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    来源:https://www.jb51.net/python/3399683md.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    本帖子中包含更多资源

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

    ×

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表