最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

利用python抓取HTML頁面數(shù)據(jù)并作可視化數(shù)據(jù)分析

 更新時間:2025年04月20日 10:16:09   作者:@半良人  
這篇文章主要為大家詳細介紹了如何利用python抓取HTML頁面數(shù)據(jù)并作可視化數(shù)據(jù)分析,文中的示例代碼講解詳細,感興趣的小伙伴可以參考一下

本文所展示的代碼是一個完整的數(shù)據(jù)采集、處理與可視化工具,主要用于從指定網站下載Excel文件,解析其中的數(shù)據(jù),并生成投資者數(shù)量的趨勢圖表。以下是代碼的主要功能模塊及其作用:

1.網頁數(shù)據(jù)獲取

使用fetch_html_page函數(shù)從目標網站抓取HTML頁面內容。

通過parse_html_for_excel_links解析HTML內容,提取所有Excel文件鏈接。

利用parse_html_for_max_page解析最大分頁數(shù),確保能夠遍歷所有頁面。

2.文件下載與存儲

download_excel_file負責根據(jù)Excel文件的URL下載文件并保存到本地指定路徑。

download_excel_data實現(xiàn)批量下載功能,支持多頁數(shù)據(jù)的完整采集。

3.數(shù)據(jù)讀取與處理

read_excel_file使用pandas庫讀取Excel文件內容。
process_excel_data將Excel數(shù)據(jù)轉換為字典格式,便于后續(xù)處理。
process_downloaded_files批量處理下載的Excel文件,提取關鍵數(shù)據(jù)并存儲為列表。

4.數(shù)據(jù)可視化

plot_investor_trends利用matplotlib繪制雙Y軸折線圖,展示個人投資者和機構投資者的數(shù)量變化趨勢。

圖表包含日期、個人投資者數(shù)量(萬名)和機構投資者數(shù)量(家),并通過不同顏色區(qū)分數(shù)據(jù)系列。

整體流程

代碼從指定網站抓取數(shù)據(jù),自動下載相關Excel文件。

解析Excel文件中的投資者數(shù)據(jù),并生成趨勢圖表以直觀展示數(shù)據(jù)變化。

import warnings

import requests
from bs4 import BeautifulSoup
import pandas as pd
import os
import re
import matplotlib

# 設置matplotlib的字體配置,以支持中文顯示
matplotlib.rcParams['font.sans-serif'] = ['SimHei']  # 或者 ['Microsoft YaHei']
matplotlib.rcParams['axes.unicode_minus'] = False
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt


def fetch_html_page(url):
    """
    獲取HTML頁面內容。

    參數(shù):
    url (str): 目標網頁的URL。

    返回:
    str: 頁面的HTML內容,如果請求失敗則返回None。
    """
    headers = {
        "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"
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        print(f"成功獲取頁面: {url}")
        return response.text
    else:
        print(f"Error: {response.status_code}, {response.text}")
        return None


def parse_html_for_excel_links(html_content):
    """
    解析HTML內容中的Excel鏈接。

    參數(shù):
    html_content (str): HTML頁面內容。

    返回:
    list: 包含所有找到的Excel文件鏈接的列表。
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    excel_links = []
    for a_tag in soup.find_all('a', href=True):
        href = a_tag.get('href')
        if href and href.endswith('.xlsx'):
            excel_links.append(href)
    return excel_links


def parse_html_for_max_page(html_content):
    """
    解析HTML內容以找到最大頁面數(shù)。

    參數(shù):
    html_content (str): HTML頁面內容。

    返回:
    int: 最大頁面數(shù)。
    """
    soup = BeautifulSoup(html_content, 'html.parser')
    max_page = 1
    for a_tag in soup.find_all('a', class_='pagingNormal'):
        onclick = a_tag.get('onclick')
        if onclick:
            match = re.search(r"'(/test/j/[^']+)'", onclick)
            if match:
                page_number = match.group(1).split('-')[-1].split('.')[0]
                max_page = max(max_page, int(page_number))
    return max_page


def download_excel_file(url, save_path):
    """
    下載Excel文件并保存到指定路徑。

    參數(shù):
    url (str): Excel文件的URL。
    save_path (str): 文件的保存路徑。
    """
    headers = {
        "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"
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        with open(save_path, 'wb') as f:
            f.write(response.content)
        print(f"下載完成: {save_path}")
    else:
        print(f"Error: {response.status_code}, {response.text}")


def download_excel_data():
    """
    下載所有Excel數(shù)據(jù)文件。
    """
    base_url = 'https://test/index.html'  # 替換為實際網頁地址
    current_url = base_url
    page_number = 1

    html_content = fetch_html_page(current_url)
    if not html_content:
        return

    max_page = parse_html_for_max_page(html_content)
    print(f"最大頁面數(shù): {max_page}")

    while page_number <= max_page:
        print(f"正在處理第 {page_number} 頁: {current_url}")
        html_content = fetch_html_page(current_url)
        if not html_content:
            break

        excel_links = parse_html_for_excel_links(html_content)
        if not excel_links:
            print("未找到Excel鏈接。")
            break

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

        if page_number < max_page:
            next_page_link = f"/test/d2bb5c19-{page_number + 1}.html"
            current_url = f"https://www.test.cn{next_page_link}"
            page_number += 1
        else:
            print("沒有更多頁面。")
            break


def read_excel_file(file_path):
    """
    讀取Excel文件內容。

    參數(shù):
    file_path (str): Excel文件的路徑。

    返回:
    DataFrame: 讀取到的Excel文件內容,如果讀取失敗則返回None。
    """
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", UserWarning)
            df = pd.read_excel(file_path, engine='openpyxl', header=None)
        return df
    except Exception as e:
        print(f"讀取Excel文件時出錯: {e}")
        return None


def process_excel_data(df):
    """
    處理Excel數(shù)據(jù),將其轉換為字典格式。

    參數(shù):
    df (DataFrame): Excel文件內容。

    返回:
    dict: 轉換后的字典數(shù)據(jù)。
    """
    if df is None:
        return {}

    # 處理合并單元格
    # df = df.fillna(method='ffill').fillna(method='bfill')

    # 將數(shù)據(jù)轉換為字典
    data_dict = {}
    current_section = None
    for index, row in df.iterrows():
        if index == 1:  # 第二行
            key = row[1]
            if pd.isnull(key):
                key = df.iloc[1, 0]
            value = row[2] if pd.notnull(row[2]) else None
            data_dict[key] = value
        elif index > 1:
            if pd.notnull(row[0]):
                current_section = row[0]
                data_dict[current_section] = {}
            if pd.notnull(row[1]):
                key = row[1]
                value = row[2] if pd.notnull(row[2]) else None
                data_dict[current_section][key] = value

    return data_dict


def process_downloaded_files(directory):
    """
    處理下載的Excel文件,提取數(shù)據(jù)。

    參數(shù):
    directory (str): 存放下載文件的目錄路徑。

    返回:
    list: 包含所有處理后的數(shù)據(jù)字典的列表。
    """
    data_list = []
    for filename in os.listdir(directory):
        if filename.endswith('.xlsx'):
            file_path = os.path.join(directory, filename)
            df = read_excel_file(file_path)
            if df is not None:
                print(f"處理文件: {filename}")
                data_dict = process_excel_data(df)
                print(data_dict)  # 打印處理后的字典
                data_list.append(data_dict)
    return data_list


def plot_investor_trends(data_list):
    """
    繪制投資者數(shù)量趨勢圖。

    參數(shù):
    data_list (list): 包含投資者數(shù)據(jù)的列表。
    """
    # 提取時間值和投資者數(shù)量
    dates = []
    individual_investors = []
    institutional_investors = []

    for data_dict in data_list:
        date_str = data_dict['統(tǒng)計指標']
        date = pd.to_datetime(date_str)
        dates.append(date)
        individual_investors.append(data_dict['證券公司開展業(yè)務情況']['個人投資者數(shù)量(萬名)'])
        institutional_investors.append(data_dict['證券公司開展業(yè)務情況']['機構投資者數(shù)量(家)'])

    # 創(chuàng)建折線圖
    fig, ax1 = plt.subplots(figsize=(10, 6))

    # 繪制個人投資者數(shù)量
    color = 'tab:red'
    ax1.set_xlabel('日期')
    ax1.set_ylabel('個人投資者數(shù)量(萬名)', color=color)
    ax1.plot(dates, individual_investors, color=color, label='個人投資者數(shù)量(萬名)', marker='o')
    ax1.tick_params(axis='y', labelcolor=color)

    # 創(chuàng)建第二個 Y 軸
    ax2 = ax1.twinx()  # 共享 X 軸

    # 繪制機構投資者數(shù)量
    color = 'tab:blue'
    ax2.set_ylabel('機構投資者數(shù)量(家)', color=color)
    ax2.plot(dates, institutional_investors, color=color, label='機構投資者數(shù)量(家)', marker='o')
    ax2.tick_params(axis='y', labelcolor=color)

    # 設置標題和圖例
    fig.tight_layout()  # 調整子圖參數(shù),防止標簽重疊
    plt.title('投資者數(shù)量趨勢')
    fig.legend(loc='upper left', bbox_to_anchor=(0.1, 0.9))

    # 顯示圖形
    plt.show()


# 調用函數(shù)繪制投資者趨勢圖
plot_investor_trends(process_downloaded_files('downloads'))

到此這篇關于利用python抓取HTML頁面數(shù)據(jù)并作可視化數(shù)據(jù)分析的文章就介紹到這了,更多相關python抓取HTML頁面數(shù)據(jù)內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • Python簡直是萬能的,這5大主要用途你一定要知道?。ㄍ扑])

    Python簡直是萬能的,這5大主要用途你一定要知道!(推薦)

    這篇文章主要介紹了Python主要用途,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-04-04
  • Python?urllib庫的使用指南詳解

    Python?urllib庫的使用指南詳解

    所謂網頁抓取,就是把URL地址中指定的網絡資源從網絡流中讀取出來,保存到本地。?在Python中有很多庫可以用來抓取網頁,本文將講解其中的urllib庫,感興趣的可以了解一下
    2022-04-04
  • Python如何快速生成本項目的requeirments.txt實現(xiàn)

    Python如何快速生成本項目的requeirments.txt實現(xiàn)

    本文主要介紹了Python如何快速生成本項目的requeirments.txt實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-03-03
  • python 申請內存空間,用于創(chuàng)建多維數(shù)組的實例

    python 申請內存空間,用于創(chuàng)建多維數(shù)組的實例

    今天小編就為大家分享一篇python 申請內存空間,用于創(chuàng)建多維數(shù)組的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • 深入了解Python枚舉類型的相關知識

    深入了解Python枚舉類型的相關知識

    這篇文章主要介紹了深入了解Python枚舉類型的相關知識,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-07-07
  • 基于Python實現(xiàn)n-gram文本生成的示例代碼

    基于Python實現(xiàn)n-gram文本生成的示例代碼

    N-gram是自然語言處理中常用的技術,它可以用于文本生成、語言模型訓練等任務,本文主要介紹了如何在Python中實現(xiàn)n-gram文本生成,需要的可以參考下
    2024-01-01
  • Python matplotlib繪制散點圖的實例代碼

    Python matplotlib繪制散點圖的實例代碼

    這篇文章主要給大家介紹了關于Python matplotlib繪制散點圖的相關資料,所謂散點圖就是反映兩組變量每個數(shù)據(jù)點的值,并且從散點圖可以看出它們之間的相關性,需要的朋友可以參考下
    2021-06-06
  • python實現(xiàn)百度語音識別api

    python實現(xiàn)百度語音識別api

    這篇文章主要為大家詳細介紹了python實現(xiàn)百度語音識別api,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • python 實現(xiàn)求解字符串集的最長公共前綴方法

    python 實現(xiàn)求解字符串集的最長公共前綴方法

    今天小編就為大家分享一篇python 實現(xiàn)求解字符串集的最長公共前綴方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-07-07
  • 如何在Python中自定義異常類與異常處理機制

    如何在Python中自定義異常類與異常處理機制

    在Python編程中,異常處理是一種重要的編程范式,它允許我們在程序運行時檢測并處理錯誤,本文將介紹如何在Python中編寫自定義的異常類,并詳細解釋Python的異常處理機制,感興趣的朋友一起看看吧
    2024-06-06

最新評論

西丰县| 建平县| 汤原县| 高雄县| 昌黎县| 梁平县| 齐齐哈尔市| 奇台县| 安丘市| 海淀区| 辽阳县| 海宁市| 金堂县| 安国市| 宜章县| 五指山市| 阿克| 郸城县| 元朗区| 蒙自县| 天津市| 曲周县| 广东省| 武夷山市| 玛沁县| 台前县| 老河口市| 扶风县| 信丰县| 正镶白旗| 蓬莱市| 农安县| 涿州市| 碌曲县| 大姚县| 昭平县| 荥阳市| 松原市| 贵德县| 临安市| 永泰县|