您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python爬虫爬取并简单分析A股公司数据
## 一、引言
在金融数据分析领域,获取上市公司基础数据是开展研究的重要前提。本文将演示如何通过Python爬虫技术从公开数据源抓取A股上市公司基本信息,并使用pandas进行简单的数据分析。整个过程涉及数据采集、清洗、存储和分析四个关键环节。
## 二、技术工具准备
需要安装以下Python库:
```python
import requests # 网络请求
from bs4 import BeautifulSoup # HTML解析
import pandas as pd # 数据分析
import sqlite3 # 数据库存储
import matplotlib.pyplot as plt # 数据可视化
我们选取东方财富网的上市公司列表页作为数据源:
http://quote.eastmoney.com/center/gridlist.html#sh_a_board
def get_stock_list():
url = "http://quote.eastmoney.com/center/gridlist.html#sh_a_board"
headers = {'User-Agent': 'Mozilla/5.0'}
try:
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 解析表格数据
table = soup.find('table', {'class': 'table_bg001'})
rows = table.find_all('tr')[1:] # 跳过表头
stock_data = []
for row in rows:
cols = row.find_all('td')
data = {
'代码': cols[1].text.strip(),
'名称': cols[2].text.strip(),
'最新价': float(cols[3].text),
'涨跌幅': cols[4].text.strip(),
'所属行业': cols[5].text.strip(),
'市盈率': float(cols[6].text) if cols[6].text != '-' else None
}
stock_data.append(data)
return pd.DataFrame(stock_data)
except Exception as e:
print(f"数据获取失败: {str(e)}")
return None
将数据保存到SQLite数据库:
def save_to_db(df, db_name='stocks.db'):
conn = sqlite3.connect(db_name)
df.to_sql('a_stock', conn, if_exists='replace', index=False)
conn.close()
df = get_stock_list()
print(f"共获取{len(df)}家上市公司数据")
print(df.describe())
industry_dist = df['所属行业'].value_counts().head(10)
plt.figure(figsize=(10,6))
industry_dist.plot(kind='bar')
plt.title('A股上市公司行业分布TOP10')
plt.xlabel('行业')
plt.ylabel('公司数量')
plt.xticks(rotation=45)
plt.tight_layout()
plt.savefig('industry_dist.png')
pe_analysis = df[df['市盈率'] > 0]['市盈率']
plt.figure(figsize=(10,6))
plt.hist(pe_analysis, bins=50, range=(0, 100))
plt.title('A股上市公司市盈率分布')
plt.xlabel('市盈率')
plt.ylabel('公司数量')
plt.savefig('pe_distribution.png')
通过本文介绍的Python爬虫技术,我们实现了从数据采集到基础分析的全流程。这种方法不仅适用于金融数据,稍作修改也可应用于其他领域的数据获取需求。需要注意的是,在实际应用中应当遵守相关法律法规和网站的使用条款。
提示:完整代码已上传至GitHub仓库(示例地址:github.com/username/stock_spider) “`
(注:实际运行时需要根据目标网站结构调整解析逻辑,本文代码为示例框架。全文约850字)
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。