1 # 爬虫
2 # 该项目是爬取天天基金网某只基金的净值数据
3
4 # 1.引入包
5 # 网络请求
6 import json
7
8 import requests
9 # 正则
10 import re
11 # 数据分析工具
12 import pandas as pd
13
14 # 获取基金净值数据方法,参数是:基金名称,代码,页面数
15 def get_data(name,code,page=11):
16 # 定义一个空的列表,存放每一页的数据
17 df_list = []
18 # for循环用来获取不同页码的数据,这里循环10次
19 for index in range(1, page):
20 # 2.请求的url地址或者接口,基金代码,页面数使用花括号占位
21 url = "http://api.fund.eastmoney.com/f10/lsjz?callback=jQuery18306600264369919882_1675428357095&fundCode={}&pageIndex={}&pageSize=20&startDate=&endDate=&_=1675428744359".format(code, index)
22
23 # 3.请求所需要的请求头内容
24 headers = {
25 "Host":"api.fund.eastmoney.com",
26 # 防盗链 确定访问来路是否非法
27 "Referer":"http://fundf10.eastmoney.com/",
28 # 身份验证,模拟浏览器发出
29 "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.76"
30 }
31
32 # 4.发送请求
33 resp = requests.get(url, headers=headers)
34
35 # 5.打印获取的数据
36 data = resp.text
37 print(data)
38
39
40 # 6.通过正则表达式获取只想要的数据
41 data = re.findall("\((.*?)\)", data)
42 print(data)
43
44 # 7.将数据转换成json格式
45 data = json.loads(data[0])["Data"]["LSJZList"]
46 print(data)
47
48 # 8.使用pandas格式化数据
49 df = pd.DataFrame(data)
50 # print(df)
51
52 # 9.将每一页数据添加到列表中
53 df_list.append(df)
54
55 # 10.打印列表中的所有数据
56 # print(df_list)
57
58 # 11.合并列表中的数据
59 df_data = pd.concat(df_list)
60 print(df_data)
61
62 # 12.将数据保存到csv中,行号不保存
63 df_data.to_csv("{}.csv".format(name), index=False)