Python采集天天基金數(shù)據(jù)掌握最新基金動向
案例實現(xiàn)流程
思路分析:
- 需要什么數(shù)據(jù)?需要的數(shù)據(jù)在哪里?
代碼實現(xiàn):
- 發(fā)送請求
- 獲取數(shù)據(jù)
- 解析數(shù)據(jù)
- 多頁爬取
- 保存數(shù)據(jù)
知識點:
requests
發(fā)送請求- 開發(fā)者工具的使用
json
類型數(shù)據(jù)解析- 正則表達式的使用
開發(fā)環(huán)境:
- 版 本:python 3.8
- 編輯器:pycharm 2021.2
本次目標(biāo):
一、分析網(wǎng)站
第一步:打開開發(fā)者工具,按F12,或者右鍵點擊檢查
第二步:刷新網(wǎng)站,點擊搜索工具,在搜索框內(nèi)輸入基金代碼,點擊搜索
第三步:找到數(shù)據(jù)所在的真實url
二、開始代碼
導(dǎo)入模塊:
import requests ? ? import re import csv
發(fā)送請求:
url = f'http://fund.eastmoney.com/data/rankhandler.aspx?op=ph&dt=kf&ft=all&rs=&gs=0&sc=6yzf&st=desc&sd=2020-12-16&ed=2021-12-16&qdii=&tabSubtype=,,,,,&pi=1&pn=50&dx=1' headers = { ? ? 'Cookie': 'HAList=a-sz-300059-%u4E1C%u65B9%u8D22%u5BCC; em_hq_fls=js; qgqp_b_id=7b7cfe791fce1724e930884be192c85e; _adsame_fullscreen_16928=1; st_si=59966688853664; st_asi=delete; st_pvi=79368259778985; st_sp=2021-12-07%2014%3A33%3A35; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=3; st_psi=20211216201351423-112200312936-0028256540; ASP.NET_SessionId=miyivgzxegpjaya5waosifrb', ? ? 'Host': 'fund.eastmoney.com', ? ? 'Referer': 'http://fund.eastmoney.com/data/fundranking.html', ? ? 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36', } response = requests.get(url=url, headers=headers)
獲取數(shù)據(jù):
data = response.text
解析數(shù)據(jù) 篩選數(shù)據(jù):
data_str = re.findall('\[(.*?)\]', data)[0]
轉(zhuǎn)變數(shù)據(jù)類型:
tuple_data = eval(data_str) for td in tuple_data: ? ? # 把td 變成列表 ? ? td_list = td.split(',')
翻頁:
分析不同頁數(shù)url變化規(guī)律
for page in range(1, 193): ? ? print(f'-------------------------正在爬取第{page}頁內(nèi)容-----------------------') ? ? url = f'http://fund.eastmoney.com/data/rankhandler.aspx?op=ph&dt=kf&ft=all&rs=&gs=0&sc=6yzf&st=desc&sd=2020-12-16&ed=2021-12-16&qdii=&tabSubtype=,,,,,&pi={page}&pn=50&dx=1'
保存數(shù)據(jù):
with open('基金.csv', mode='a', encoding='utf-8', newline='') as f: ? ? csv_write = csv.writer(f) ? ? csv_write.writerow(td_list) print(td)
三、運行代碼,得到數(shù)據(jù)
到此這篇關(guān)于Python采集天天基金數(shù)據(jù)掌握最新基金動向的文章就介紹到這了,更多相關(guān)Python采集天天基金數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Django獲取model中的字段名和字段的verbose_name方式
這篇文章主要介紹了Django獲取model中的字段名和字段的verbose_name方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05python機器學(xué)習(xí)理論與實戰(zhàn)(五)支持向量機
這篇文章主要為大家詳細介紹了python機器學(xué)習(xí)理論與實戰(zhàn)第五篇,支持向量機的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01