You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:使用pandas导出文件时遇AttributeError,list对象无to_csv属性

解决AttributeError: 'list' object has no attribute 'to_csv'错误

问题核心

你遇到的错误是因为write_file函数接收的参数是列表,但to_csv、to_excel这些都是pandas DataFrame独有的方法,列表没有这些属性。

具体来说,你的get_cmvp_data函数最后返回的是detail_urls_lst(一个空列表),而不是你处理好的过滤后的数据表(DataFrame)。

修改步骤

  1. 修正返回值:在get_cmvp_data函数中,把最后返回的detail_urls_lst改成你过滤后的DataFrame df_filtered(如果需要原始数据就返回df)。
  2. 清理冗余代码:删除没用的detail_urls_lst和sunset_date_lst定义,避免混淆。
  3. 验证数据传递:确保main函数中cmvp_data接收的是DataFrame类型。

修改后的完整代码

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


def main():
    certs_url = "https://csrc.nist.gov/projects/cryptographic-module-validation-program/validated-modules/search/all"

    # Data refresh from the NIST site
    data = get_html(certs_url)
    cmvp_data = get_cmvp_data(data)
    write_file('txt', cmvp_data)


def get_html(url):
    # make request to URL and convert to BS obj
    req = requests.get(url)
    soup = BeautifulSoup(req.content, 'html.parser')
    return soup


def get_cmvp_data(cmvp_content):
    # --- Build CMVP dataframe ---
    search_tbl = cmvp_content.find_all('table', id='searchResultsTable')
    # convert HTML table to df obj
    cert_table = pd.read_html(str(search_tbl))
    df = cert_table[0]
    # column headers - replace spaces with '_'
    df.columns = [column.replace(" ", "_") for column in df.columns]

    # --- Filter tech vendors ---
    df_filtered = df.loc[(df['Vendor_Name'].str.contains('Splunk', case=False, na=False)) |
                df['Vendor_Name'].str.contains('Trend Micro', case=False, na=False) |
                df['Vendor_Name'].str.contains('Yubico', case=False, na=False) |
                df['Vendor_Name'].str.contains('Red Hat', case=False, na=False) |
                df['Vendor_Name'].str.contains('Palo Alto', case=False, na=False) |
                df['Vendor_Name'].str.contains('Microsoft', case=False, na=False) |
                df['Vendor_Name'].str.contains('Cisco', case=False, na=False)]

    for i in df['Certificate_Number']:
        print(i)

    # Return filtered DataFrame instead of empty list
    return df_filtered


def write_file(output_type, df_data):
    # -- Write file ---
    if output_type == 'txt':
        # Export df to delimited text file
        df_data.to_csv('output.txt', sep='|')
    elif output_type == 'excel':
        # Export to Excel file
        df_data.to_excel('output.xlsx')
    else:
        # Export df to HTML file
        result = df_data.to_html()
        with open('df.html', 'w') as func:
            func.write(result)
    print('Export complete')
    return


if __name__ == "__main__":
    main()

额外优化说明

  • 把open('df.html', 'w')改成with语句,自动关闭文件,避免资源泄漏。
  • 整理了注释表述,更清晰易懂。
  • 删除了write_file函数参数列表末尾多余的逗号,语法更规范。

内容的提问来源于stack exchange,提问作者Mitchell Privett

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:36:23