在大数据时代,企业财务数据对于税务分析至关重要。通过对企业的财务报表进行分析,可以洞察企业的经营状况,为税务合规性检查、风险评估以及政策制定提供依据。本实验将介绍如何使用Python爬取证券之星上的特定公司的资产负债表、利润表、现金流量表,并探讨这些数据在税务大数据分析中的作用。
浪潮软件的股票代码是600756 找到我们需要的网站
观察网站URL可知,'/xxxxx_600756.shtml' 路径中的 xxxxx_600756 包含了股票代码 600756,表明这是关于浪潮软件公司的具体页面。'600756'嵌入在路径中的股票代码表明该页面特定于浪潮软件公司。这种命名方式适用于其他公司的页面,只需替换不同的股票代码即可访问相应的公司信息页面。目标页面如下:
打开目标网页: 打开浏览器,进入目标网页:证券之星 - 浪潮软件。
进入开发者工具: 按 F12 打开开发者工具,或者右键点击页面并选择“检查”或“检查元素”。
使用元素选择器: 在开发者工具中,选择元素选择器(通常是一个鼠标图标)。然后在页面上点击你想要抓取的内容,这将直接定位到相应的 HTML 元素。
获取选择器: 在开发者工具中,可以看到元素的 HTML 代码。右键点击该元素,在弹出菜单中选择“复制” -> 复制XPath。
我们想要爬取的内容位于 //*[@id="sta_3"]/div[1]/div[2]/table 路径下
requests 用于发送 HTTP 请求。 lxml.html 用于解析和处理 HTML。 函数 get_table_content:
设置请求头以模拟浏览器行为。 发送 GET 请求以获取网页内容。 使用 lxml.html.fromstring 解析网页内容为树结构。 使用 xpath 方法找到指定的 table 元素。 使用 html.tostring 方法将元素转换为字符串。
定义一个函数:get_table_content,函数的参数为stock_code,代表企业的股票代码。用户输入股票代码以指定要爬取的网页。 调用 get_table_content 函数爬取并打印表格内容。
import requests
from lxml import html
def get_table_content_balance(stock_code):
# 目标URL
url = f'https://stock.quote.stockstar.com/finance/balance_{stock_code}.shtml'
# 请求头,模拟浏览器行为
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:
# 解析HTML
tree = html.fromstring(response.content)
# 使用XPath找到目标table元素
table_elements = tree.xpath('//*[@id="sta_3"]/div[1]/div[2]') #刚刚复制的XPath路径
if table_elements:
# 提取并返回table内容
table_content = html.tostring(table_elements[0], encoding='unicode')
return table_content
else:
return "未找到目标table元素"
else:
return f'请求失败,状态码: {response.status_code}'
# 输入企业股票代码
stock_code = input("请输入企业股票代码: ")
table_content_balance = get_table_content_balance(stock_code)
if table_content_balance:
print("表格内容:")
print(table_content_balance)
我们已经将爬取出来的表格内容存储在table_content中,下面对爬取的 HTML 表格数据进行数据清洗并转换为结构化数据(如 EXCEL 文件),我们需要做以下几步:
#导入新的类库
from bs4 import BeautifulSoup
import pandas as pd
# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(table_content_balance, 'html.parser')
# 提取表格中的所有行
rows = soup.find_all('tr')
# 创建一个列表来存储所有的数据
data = []
# 遍历每一行
for row in rows:
cols = row.find_all('td') # 找到所有的 td 标签
cols = [ele.text.strip() for ele in cols] # 提取文本,并去除前后空格
data.append([ele for ele in cols if ele]) # 添加数据到列表
#预览数据
print (data)
**提示:** 为保证后台Excel表格命名不冲突,将保存Excel部分代码以"""注释掉了,如需运行,则将下面代码段中前后的"""去掉,然后运行。
"""
# 将信息保存在excel表格中
# 创建 pandas DataFrame,设置第一行为列名
df = pd.DataFrame(data[1:], columns=data[0])
print (df)
# 定义 Excel 文件名和工作表名
file_name = f'{stock_code}balance.xlsx'
sheet_name = 'balance'
# 将 DataFrame 写入 Excel 文件的指定工作表中
with pd.ExcelWriter(file_name, engine='openpyxl') as writer:
df.to_excel(writer, sheet_name=sheet_name, index=False)
"""
#抽取利润表
def get_table_content_profit(stock_code):
# 目标URL
url = f'https://stock.quote.stockstar.com/finance/profit_{stock_code}.shtml'
# 请求头,模拟浏览器行为
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:
# 解析HTML
tree = html.fromstring(response.content)
# 使用XPath找到目标table元素
table_elements = tree.xpath('//*[@id="sta_3"]/div[1]/div/div[2]/table')
if table_elements:
# 提取并返回table内容
table_content = html.tostring(table_elements[0], encoding='unicode')
return table_content
else:
return "未找到目标table元素"
else:
return f'请求失败,状态码: {response.status_code}'
table_content_profit = get_table_content_profit(stock_code)
if table_content_profit:
print("表格内容:")
print(table_content_profit)
# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(table_content_profit, 'html.parser')
# 提取表格中的所有行
rows = soup.find_all('tr')
# 创建一个列表来存储所有的数据
data = []
# 遍历每一行
for row in rows:
cols = row.find_all('td') # 找到所有的 td 标签
cols = [ele.text.strip() for ele in cols] # 提取文本,并去除前后空格
data.append([ele for ele in cols if ele]) # 添加数据到列表
#预览数据
print (data)
**提示:** 为保证后台Excel表格命名不冲突,将保存Excel部分代码以"""注释掉了,如需运行,则将下面代码段中前后的"""去掉,然后运行。
"""
# 将信息保存在excel表格中
# 创建 pandas DataFrame,设置第一行为列名
df = pd.DataFrame(data[1:], columns=data[0])
print (df)
# 定义 Excel 文件名和工作表名
file_name = f'{stock_code}profit.xlsx'
sheet_name = 'profit'
# 将 DataFrame 写入 Excel 文件的指定工作表中
with pd.ExcelWriter(file_name, engine='openpyxl') as writer:
df.to_excel(writer, sheet_name=sheet_name, index=False)
"""
#抽取现金流量表
def get_table_content_cashflow(stock_code):
# 目标URL
url = f'https://stock.quote.stockstar.com/finance/cashflow_{stock_code}.shtml'
# 请求头,模拟浏览器行为
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:
# 解析HTML
tree = html.fromstring(response.content)
# 使用XPath找到目标table元素
table_elements = tree.xpath('//*[@id="sta_3"]/div[1]/div/div[2]/table')
if table_elements:
# 提取并返回table内容
table_content = html.tostring(table_elements[0], encoding='unicode')
return table_content
else:
return "未找到目标table元素"
else:
return f'请求失败,状态码: {response.status_code}'
table_content_cashflow = get_table_content_cashflow(stock_code)
if table_content_cashflow:
print("表格内容:")
print(table_content_cashflow)
# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(table_content_cashflow, 'html.parser')
# 提取表格中的所有行
rows = soup.find_all('tr')
# 创建一个列表来存储所有的数据
data = []
# 遍历每一行
for row in rows:
cols = row.find_all('td') # 找到所有的 td 标签
cols = [ele.text.strip() for ele in cols] # 提取文本,并去除前后空格
data.append([ele for ele in cols if ele]) # 添加数据到列表
#预览数据
print (data)
**提示:** 为保证后台Excel表格命名不冲突,将保存Excel部分代码以"""注释掉了,如需运行,则将下面代码段中前后的"""去掉,然后运行。
"""
# 将信息保存在excel表格中
# 创建 pandas DataFrame,设置第一行为列名
df = pd.DataFrame(data[1:], columns=data[0])
print (df)
# 定义 Excel 文件名和工作表名
file_name = f'{stock_code}cashflow.xlsx'
sheet_name = 'cashflow'
# 将 DataFrame 写入 Excel 文件的指定工作表中
with pd.ExcelWriter(file_name, engine='openpyxl') as writer:
df.to_excel(writer, sheet_name=sheet_name, index=False)
"""
import os
# 定义函数来获取表格内容
def get_table_content(stock_code):
# 目标URL
url = f'https://stock.quote.stockstar.com/corp_{stock_code}.shtml'
# 请求头,模拟浏览器行为
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:
# 解析HTML
tree = html.fromstring(response.content)
# 使用XPath找到目标table元素
table_elements = tree.xpath('//*[@id="sta_3"]/div[3]/div[1]/div[1]/div[2]/table')
if table_elements:
# 提取并返回table内容
table_content = html.tostring(table_elements[0], encoding='unicode')
return table_content
else:
return "未找到目标table元素"
else:
return f'请求失败,状态码: {response.status_code}'
# 主程序
def get_table_content_info(stock_code):
# 文件名
filename = f"{stock_code}info.xlsx"
# 检查文件是否存在
if not os.path.exists(filename):
# 获取表格内容
table_content = get_table_content(stock_code)
if table_content != "未找到目标table元素" and "请求失败" not in table_content:
# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(table_content, 'html.parser')
# 提取表格中的所有行
rows = soup.find_all('tr')
# 创建一个列表来存储所有的数据
data = []
# 遍历每一行
for row in rows:
cols = row.find_all('td') # 找到所有的 td 标签
cols = [ele.text.strip() for ele in cols] # 提取文本,并去除前后空格
data.append([ele for ele in cols if ele]) # 添加数据到列表
# 将数据转换为DataFrame
df = pd.DataFrame(data[1:], columns=data[0]) # 假设第一行为表头
# 保存到Excel文件
df.to_excel(filename, index=False)
else:
print(table_content)
else:
print("File already exists. Skipping data extraction.")
# 运行主程序
get_table_content_info(stock_code)
**提示:** 为保证后台Excel表格命名不冲突,将保存Excel部分代码以"""注释掉了,如需运行,则将下面代码段中前后的"""去掉,然后运行。
"""
# 定义 Excel 文件名
excel_files = [f'{stock_code}info.xlsx',f'{stock_code}balance.xlsx', f'{stock_code}profit.xlsx',f'{stock_code}cashflow.xlsx' ]
# 定义对应的工作表名
sheet_names = ['企业信息', '资产负债表', '利润表', '现金流量表']
# 创建一个 ExcelWriter 对象,用于写入新的 Excel 文件
with pd.ExcelWriter(f'{stock_code}.xlsx', engine='openpyxl') as writer:
# 遍历每个文件和对应的工作表名
for file, sheet in zip(excel_files, sheet_names):
# 读取每个 Excel 文件
if os.path.exists(file):
df = pd.read_excel(file)
# 将 DataFrame 写入新的工作表
df.to_excel(writer, sheet_name=sheet, index=False)
else:
print(f"文件 {file} 不存在,跳过该文件。")
print(f"所有文件已成功合并到 {stock_code} 中,并分别存储在不同的工作表中。")
# 删除原始的 Excel 文件
for file in excel_files:
if os.path.exists(file):
os.remove(file)
print(f"{file} 已删除")
else:
print(f"{file} 不存在,无法删除")
"""