python爬取基金历史净值_Python爬取天天基金网历史净值数据
type 類型,歷史凈值用lsjz表示
code 基金代碼,六位數(shù)字
sdate 開始日期,格式是yyyy-mm-dd
edate 結(jié)束日期,格式是yyyy-mm-dd
per 一頁(yè)顯示多少條記錄
為了便于分析頁(yè)面數(shù)據(jù),要保證所選擇日期范圍內(nèi)的凈值在一個(gè)頁(yè)面全部顯示,可以把per設(shè)成很大的值,比如65535。
返回的頁(yè)面數(shù)據(jù)比較簡(jiǎn)單,只有一個(gè)歷史凈值的表格和總記錄數(shù),總頁(yè)數(shù)和當(dāng)前頁(yè)數(shù)。
var apidata={ content:"
凈值日期 單位凈值 累計(jì)凈值 日增長(zhǎng)率 申購(gòu)狀態(tài) 贖回狀態(tài) 分紅送配
2018-03-02 2.3580 2.3580 0.17% 開放申購(gòu) 開放贖回
2018-03-01 2.3540 2.3540 0.56% 開放申購(gòu) 開放贖回
2018-02-28 2.3410 2.3410 -1.35% 開放申購(gòu) 開放贖回
2018-02-27 2.3730 2.3730 -2.06% 開放申購(gòu) 開放贖回
2018-02-26 2.4230 2.4230 0.29% 開放申購(gòu) 開放贖回
2018-02-23 2.4160 2.4160 -0.49% 開放申購(gòu) 開放贖回
2018-02-22 2.4280 2.4280 2.58% 開放申購(gòu) 開放贖回
",records:7,pages:1,curpage:1};
html.PNG
用BeautifulSoup庫(kù)的findAll找到tbody(表格主體)標(biāo)簽,然后在里面找tr(表格中的一行)標(biāo)簽,單元格內(nèi)容是:
td:nth-of-type(1)(第1個(gè)單元格)是凈值日期
td:nth-of-type(2)(第2個(gè)單元格)是單位凈值
td:nth-of-type(3)(第3個(gè)單元格)是累計(jì)凈值
td:nth-of-type(4)(第4個(gè)單元格)是日增長(zhǎng)率
范例代碼如下:
# -*- coding:utf-8 -*-
import requests
from bs4 import BeautifulSoup
from prettytable import *
def get_url(url, params=None, proxies=None):
rsp = requests.get(url, params=params, proxies=proxies)
rsp.raise_for_status()
return rsp.text
def get_fund_data(code, start='', end=''):
record = {'Code': code}
url = 'http://fund.eastmoney.com/f10/F10DataApi.aspx'
params = {'type': 'lsjz', 'code': code, 'page': 1, 'per': 65535, 'sdate': start, 'edate': end}
html = get_url(url, params)
soup = BeautifulSoup(html, 'html.parser')
records = []
tab = soup.findAll('tbody')[0]
for tr in tab.findAll('tr'):
if tr.findAll('td') and len((tr.findAll('td'))) == 7:
record['Date'] = str(tr.select('td:nth-of-type(1)')[0].getText().strip())
record['NetAssetValue'] = str(tr.select('td:nth-of-type(2)')[0].getText().strip())
record['ChangePercent'] = str(tr.select('td:nth-of-type(4)')[0].getText().strip())
records.append(record.copy())
return records
def demo(code, start, end):
table = PrettyTable()
table.field_names = ['Code', 'Date', 'NAV', 'Change']
table.align['Change'] = 'r'
records = get_fund_data(code, start, end)
for record in records:
table.add_row([record['Code'], record['Date'], record['NetAssetValue'], record['ChangePercent']])
return table
if __name__ == "__main__":
print demo('110022', '2018-02-22', '2018-03-02')
輸出結(jié)果如下:
+--------+------------+--------+--------+
| Code | Date | NAV | Change |
+--------+------------+--------+--------+
| 110022 | 2018-03-02 | 2.3580 | 0.17% |
| 110022 | 2018-03-01 | 2.3540 | 0.56% |
| 110022 | 2018-02-28 | 2.3410 | -1.35% |
| 110022 | 2018-02-27 | 2.3730 | -2.06% |
| 110022 | 2018-02-26 | 2.4230 | 0.29% |
| 110022 | 2018-02-23 | 2.4160 | -0.49% |
| 110022 | 2018-02-22 | 2.4280 | 2.58% |
+--------+------------+--------+--------+
總結(jié)
以上是生活随笔為你收集整理的python爬取基金历史净值_Python爬取天天基金网历史净值数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 刺客信条奥德赛黄金版和普通版有什么区别
- 下一篇: 乐播投屏怎么把声音投到电视上