以下是 Python 代码实现:

import requests
from bs4 import BeautifulSoup
import csv
import xlrd

# 读取 Excel 文件中的股票代码
def read_stock_codes(file_path):
    stock_codes = []
    workbook = xlrd.open_workbook(file_path)
    sheet = workbook.sheet_by_index(0)
    for i in range(1, sheet.nrows):
        stock_code = sheet.cell_value(i, 1)
        stock_codes.append(stock_code)
    return stock_codes

# 获取财务数据并写入 CSV 文件
def get_finance_data(stock_code):
    url = 'http://stockpage.10jqka.com.cn/{}/finance/'.format(stock_code)
    resp = requests.get(url)
    soup = BeautifulSoup(resp.text, 'html.parser')
    finance_table = soup.find('table', {'class': 'm-table J-ajax-table'})
    rows = finance_table.find_all('tr')
    csv_file = open('{}_finance.csv'.format(stock_code), 'w', encoding='utf-8-sig', newline='')
    writer = csv.writer(csv_file)
    for row in rows:
        cols = row.find_all('td')
        data = []
        for col in cols:
            data.append(col.text.strip())
        writer.writerow(data)
    csv_file.close()

# 批量获取财务数据
def batch_get_finance_data(file_path):
    stock_codes = read_stock_codes(file_path)
    for stock_code in stock_codes:
        get_finance_data(stock_code)

# 测试
batch_get_finance_data('stock_codes.xlsx')

首先,我们定义了一个函数 read_stock_codes,用于读取 Excel 文件中的股票代码,返回一个股票代码的列表。

然后,我们定义了一个函数 get_finance_data,用于获取股票对应的财务数据,并将数据写入 CSV 文件中。该函数接收一个股票代码作为参数,使用 requests 库发送 HTTP 请求,使用 BeautifulSoup 库解析 HTML 文档,获取财务数据表格并遍历表格行和列,将数据写入 CSV 文件中。

接着,我们定义了一个函数 batch_get_finance_data,用于批量获取财务数据。该函数调用 read_stock_codes 函数获取股票代码列表,然后遍历股票代码列表,调用 get_finance_data 函数获取财务数据。

最后,我们调用 batch_get_finance_data 函数,并传入 Excel 文件的路径作为参数,即可批量获取财务数据并保存到 CSV 文件中。

Python 批量爬取股票财务数据并保存到 CSV 文件

原文地址: https://www.cveoy.top/t/topic/mEAg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录