溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python如何采集基金數(shù)據(jù)

發(fā)布時間:2022-01-04 00:41:16 來源:億速云 閱讀:214 作者:柒染 欄目:開發(fā)技術(shù)

Python如何采集基金數(shù)據(jù),針對這個問題,這篇文章詳細介紹了相對應(yīng)的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

案例實現(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

本次目標:

Python如何采集基金數(shù)據(jù)

Python如何采集基金數(shù)據(jù)

一、分析網(wǎng)站

第一步:打開開發(fā)者工具,按F12,或者右鍵點擊檢查
第二步:刷新網(wǎng)站,點擊搜索工具,在搜索框內(nèi)輸入基金代碼,點擊搜索

Python如何采集基金數(shù)據(jù)

第三步:找到數(shù)據(jù)所在的真實url

Python如何采集基金數(shù)據(jù)

二、開始代碼

導(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ī)律

Python如何采集基金數(shù)據(jù)

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ù)

Python如何采集基金數(shù)據(jù)

Python如何采集基金數(shù)據(jù)

關(guān)于Python如何采集基金數(shù)據(jù)問題的解答就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI