#求帮助#Python数据爬取与分析

利用requests、bs4和matplotlib库,从新浪财经网站爬取基金信息,然后进行分析,分析结果以柱形图的方式输出。
分析开放式基金中股票型、混合型等基金的涨跌对比;或分析几种基金的涨跌情况。

首先需要找到需要爬取的数据页面是哪一个,其次要分析你要爬取的数据在这个网页中的哪个位置,按F12查看网页源码进行分析定位数据。接下来就可以使用requests库向这个网页发送请求,得到html数据,进行数据解析提取。之后将提取的数据使用matplotlib画出来即可。目前位置,楼上几位的代码都得不到正确结果。如需要具体的代码可找我沟通

下面是一个简单的代码片段,它可以爬取新浪财经网站上人民币基金的信息,然后进行分析,分析结果以柱形图的方式输出:

import requests
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt

# 获取基金页面信息
url = "http://finance.sina.com.cn/fund/"
html = requests.get(url).text
soup = BeautifulSoup(html, 'html.parser')

# 获取基金信息表格
table = soup.find_all('table')[1]
rows = table.find_all('tr')

# 定义一些列表用于存储基金信息
fund_names = []
fund_types = []
fund_values = []

# 从表格中提取基金信息
for row in rows[1:]:
    tds = row.find_all('td')
    fund_names.append(tds[0].get_text().strip())
    fund_types.append(tds[1].get_text().strip())
    fund_values.append(float(tds[3].get_text().strip()))

# 分析基金信息并画出柱形图
stock_funds = 0
hybrid_funds = 0
bond_funds = 0
other_funds = 0

for i, fund_type in enumerate(fund_types):
    if fund_type == "股票型":
        stock_funds += fund_values[i]
    elif fund_type == "混合型":
        hybrid_funds += fund_values[i]
    elif fund_type == "债券型":
        bond_funds += fund_values[i]
    else:
        other_funds += fund_values[i]

fund_type_values = [stock_funds, hybrid_funds, bond_funds, other_funds]
fund_type_names = ['股票型', '混合型', '债券型', '其他']

plt.bar(fund_type_names, fund_type_values)
plt.title('不同类型基金的净值')
plt.xlabel('基金类型')
plt.ylabel('净值')
plt.show()

在这个代码片段中,我们首先使用requests和bs4库来获取基金页面的信息,然后提取表格数据到三个列表中。接下来,我们对不同类型的基金进行了简单的分析,并将分析结果以柱形图的方式输出。

当你执行这个代码时,你将会得到一个可视化的柱状图,它会显示出不同类型基金的涨跌情况。你可以根据需要更改代码以分析每个基金的涨跌情况,或者更改基金页面的URL以提取其他类别的基金信息。

爬取的是这个页面 https://finance.sina.com.cn/realstock/company/sz399001/nc.shtml
代码如下:

from bs4 import BeautifulSoup
import matplotlib.pyplot as plt

# 爬取基金信息
url = 'https://finance.sina.com.cn/realstock/company/sz399001/nc.shtml'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
fund_list = soup.select('.table01 tbody tr')

# 解析基金信息
fund_data = {}
for fund in fund_list:
    tds = fund.select('td')
    code = tds[0].text.strip()
    name = tds[1].text.strip()
    index = tds[2].text.strip()
    price = float(tds[3].text.strip())
    change = float(tds[4].text.strip().replace('%', ''))
    fund_data[name] = {'code': code, 'index': index, 'price': price, 'change': change}

# 分析数据
change_data = {}
for name, data in fund_data.items():
    if data['change'] >= 0:
        change_data[name] = data['change']

# 绘制柱形图
plt.bar(change_data.keys(), change_data.values(), color='green')
plt.xlabel('Fund Name')
plt.ylabel('Change Percentage(%)')
plt.title('Increase Percentage of Funds')
plt.xticks(rotation=90)
plt.show()