Python副業(yè)600元,爬取金融期貨數(shù)據(jù)
任務(wù)簡介
??首先,客戶原需求是獲取https://hq.smm.cn/copper網(wǎng)站上的價(jià)格數(shù)據(jù)(注:獲取的是網(wǎng)站上的公開數(shù)據(jù)),如下圖所示:

??如果以該網(wǎng)站為目標(biāo),則需要解決的問題是“登錄”用戶,再將價(jià)格解析為表格進(jìn)行輸出即可。但是,實(shí)際上客戶核心目標(biāo)是獲取“滬銅CU2206”的歷史價(jià)格,雖然該網(wǎng)站也有提供數(shù)據(jù),但是需要“會(huì)員”才可以訪問,而會(huì)員需要氪金......

??鑒于,客戶需求僅僅是“滬銅CU2206”一項(xiàng)期貨的歷史價(jià)格,氪金會(huì)員性價(jià)比不高,因此,實(shí)際的任務(wù)目標(biāo)變?yōu)槿绾潍@取的歷史價(jià)格,目標(biāo)變?yōu)槿W(wǎng)有公開提供數(shù)據(jù)的網(wǎng)址。而最終解決該問題,是求助于萬能的百度^_^。找到了合適的網(wǎng)站,且獲取數(shù)據(jù)的難度也幾乎降到了最低難度。
解決步驟
百度搜索資源:這個(gè)步驟是整個(gè)任務(wù)完整的最難點(diǎn)(實(shí)際不難),但這里賣個(gè)關(guān)子,全文不公布最終找到的網(wǎng)站,大家試試看能否搜索到,以及花費(fèi)多少時(shí)間^_^。 解析網(wǎng)站的請求,最終找到的網(wǎng)站經(jīng)解析后,發(fā)現(xiàn)獲取數(shù)據(jù)是通過get的方式提交參數(shù)。而請求的參數(shù)如下: /price?starttime=1638545822&endtime=1654357022&classid=48,一看就知是開始時(shí)間、結(jié)束時(shí)間的時(shí)間戳,以及商品id。再解析headers,居然連cookie都不需要,說明沒有反爬!沒有反爬!沒有反爬!不得不說運(yùn)氣爆棚!解析響應(yīng)數(shù)據(jù):由于響應(yīng)數(shù)據(jù)是規(guī)整的json格式數(shù)據(jù),使用pandas的read_json直接能夠獲取dataframe格式的數(shù)據(jù),該步驟也并無難度。
代碼實(shí)現(xiàn)
??鑒于網(wǎng)站沒有反爬,且參數(shù)簡單,實(shí)際上的任務(wù)主要是規(guī)劃一下如何設(shè)計(jì)增量更新數(shù)據(jù)信息的流程,具體代碼如下:
#?-*-?coding:?utf-8?-*-
#?@author:?Lin?Wei
#?@contact:[email protected]
#?@time:?2022/6/2?8:53
"""
1.?這是爬取滬銅的程序
2. 該網(wǎng)站滬銅當(dāng)月的數(shù)據(jù)實(shí)際請求地址是:'(實(shí)際網(wǎng)址)/price?starttime={starttime}&endtime={endtime}&classid={classid}'
2.1.?starttime為起始日期的時(shí)間戳
2.2.?endtime為結(jié)束日期的時(shí)間戳
2.3.?classid為查詢商品的id
3.?該網(wǎng)址可以直接發(fā)起請求獲取數(shù)據(jù)
"""
import?time
from?datetime?import?datetime
import?pathlib?as?pl
import?requests
import?pandas?as?pd
class?Spider:
????"""
????爬取網(wǎng)站數(shù)據(jù)的爬蟲對象
????"""
????def?__init__(self,?starttime:?str?=?None,?endtime:?str?=?None,?classid:?int?=?48):
????????"""
????????初始化對象屬性
????????:param?starttime:?數(shù)據(jù)的起始日期,文本日期格式,示例?2022-1-1
????????:param?endtime:?數(shù)據(jù)的結(jié)束日期,文本日期格式,示例?2022-1-1
????????:param?classid:?商品id,默認(rèn)48
????????"""
????????self.classid?=?classid??#?商品id
????????self.data?=?pd.DataFrame()??#?初始化空dataframe
????????self.data_file?=?pl.Path('./data/hutong.xlsx')??#?爬取的數(shù)據(jù)存儲(chǔ)文件
????????#?列名字典
????????self.cols_dict?=?{
????????????'createtime':?'日期',
????????????'classid':?'商品',
????????????'start':?'開盤',
????????????'end':?'收盤',
????????????'min':?'最低',
????????????'max':?'最高',
????????????'move':?'漲跌',
????????????'move_percent':?'漲跌百分比'
????????}
????????#?商品id字典
????????self.classid_dict?=?{
????????????48:?'CU2206'
????????}
????????#?獲取爬取的開始時(shí)間與結(jié)束時(shí)間
????????self.starttime,?self.endtime?=?self.make_starttime_endtime(starttime=starttime,?endtime=endtime)
????????#?初始化需要爬取的url
????????self.url?=?'(實(shí)際地址)/price?starttime={starttime}&endtime={endtime}&classid={classid}'
????????#?初始化headers
????????self.headers?=?{
????????????'User-Agent':?'Mozilla/5.0?(Windows?NT?10.0;?Win64;?x64)?AppleWebKit/537.36?(KHTML,?like?Gecko)?Chrome/99.0.4844.51?Safari/537.36',
????????????'Accept':?'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
????????????'Accept-Encoding':?'gzip,?deflate,?br',
????????????'Accept-Language':?'zh-CN,zh;q=0.9',
????????}
????def?make_starttime_endtime(self,?starttime:?str,?endtime:?str):
????????"""
????????制作起始日期,邏輯如下;
????????1.如果有傳入日期,則根據(jù)傳入的日期,定義起始日期與結(jié)束日期
????????2.如果未傳入?yún)?shù),則根據(jù)讀取到的歷史數(shù)據(jù)文件中的最大日期作為起始日期、以當(dāng)前日期為結(jié)束日期
????????3.如果未讀取到歷史數(shù)據(jù)文件,或文件中的最大日期為空,則以2021-1-1作為起始日期,以當(dāng)前日期作為結(jié)束日期
????????:param?starttime:?數(shù)據(jù)的起始日期,文本日期格式,示例?2022-1-1
????????:param?endtime:?數(shù)據(jù)的結(jié)束日期,文本日期格式,示例?2022-1-1
????????:return:
????????"""
????????self.read_data()??#?讀取歷史爬取數(shù)據(jù)
????????now?=?datetime.now()??#?獲取當(dāng)前時(shí)間的時(shí)間戳整數(shù)部分
????????if?endtime:??#?如果非空
????????????year,?month,?day?=?endtime.split('-')
????????????endtime?=?int(now.replace(year=int(year),?month=int(month),?day=int(day)).timestamp())
????????else:
????????????endtime?=?int(now.timestamp())
????????if?starttime:
????????????year,?month,?day?=?starttime.split('-')
????????????starttime?=?int(now.replace(year=int(year),?month=int(month),?day=int(day)).timestamp())
????????else:
????????????starttime?=?self.data['日期'].max()
????????????if?pd.isnull(starttime):??#?如果開始日期是空值
????????????????starttime?=?int(now.replace(year=2021,?month=1,?day=1).timestamp())
????????????else:
????????????????starttime?=?int(
????????????????????now.replace(year=starttime.year,?month=starttime.month,?day=starttime.day).timestamp())
????????return?starttime,?endtime
????def?read_data(self):
????????"""
????????讀取歷史數(shù)據(jù)
????????:return:
????????"""
????????if?self.data_file.is_file():??#?如果歷史數(shù)據(jù)文件存在
????????????self.data?=?pd.read_excel(self.data_file)
????????????self.data['日期']?=?self.data['日期'].map(lambda?x:?x.date())
????????else:??#?如果歷史數(shù)據(jù)文件不存在,那么初始化一個(gè)只有列名的dataframe,
????????????self.data?=?pd.DataFrame(self.cols_dict.values()).set_index(0).T
????def?crawl_data(self):
????????"""
????????爬取數(shù)據(jù)
????????:return:
????????"""
????????retry_times?=?0
????????while?retry_times?10:??#?重試10次
????????????try:
????????????????res?=?requests.get(
????????????????????self.url.format(starttime=self.starttime,?endtime=self.endtime,?classid=self.classid),
????????????????????headers=self.headers,?timeout=30)
????????????????if?res.status_code?==?200:??#?如果返回狀態(tài)至為200,進(jìn)行后續(xù)數(shù)據(jù)加工
????????????????????data?=?pd.read_json(res.text)??#?json格式轉(zhuǎn)換為dataframe
????????????????????data['createtime']?=?data['createtime'].map(lambda?x:?datetime.fromtimestamp(x).date())??#?時(shí)間戳日期轉(zhuǎn)換為日期
????????????????????data.rename(columns=self.cols_dict,?inplace=True)??#?重命名列
????????????????????data?=?data[self.cols_dict.values()]??#?截取需要的列
????????????????????data['商品']?=?self.classid_dict.get(self.classid,?'未知商品,請維護(hù)classid_dict字典')??#?轉(zhuǎn)換商品名
????????????????????data.sort_values(by=['商品',?'日期'],?ascending=True,?inplace=True)??#?按日期升序排序
????????????????????return?data
????????????????else:
????????????????????retry_times?+=?1
????????????????????print(f'返回狀態(tài)碼是?{res.status_code},等待5秒后重新發(fā)起請求')
????????????????????time.sleep(5)
????????????except?Exception?as?e:
????????????????retry_times?+=?1
????????????????print(f'請求發(fā)生錯(cuò)誤,等待5秒后重新發(fā)起請求,?錯(cuò)誤信息:?{e}')
????????????????time.sleep(5)
????????print('發(fā)起10次請求均未能獲得數(shù)據(jù)')
????????return?pd.DataFrame()
????def?concat_and_write_data(self,?data:?pd.DataFrame):
????????"""
????????合并數(shù)據(jù),并將數(shù)據(jù)寫入文件
????????:param?data:?傳入需要合并的數(shù)據(jù)
????????:return:
????????"""
????????self.data?=?pd.concat([self.data,?data])??#?合并數(shù)據(jù)
????????self.data?=?self.data.drop_duplicates(['日期',?'商品'],?keep='last')??#?數(shù)據(jù)根據(jù)商品名稱與日期進(jìn)行去重,每次保留最新的記錄
????????if?not?self.data_file.parent.is_dir():??#?檢查數(shù)據(jù)文件的目錄是否存在,如不存在則創(chuàng)建新目錄
????????????self.data_file.parent.mkdir()
????????self.data.to_excel(self.data_file,?index=False,?encoding='utf-8')??#?輸出數(shù)據(jù)為excel格式
????def?run(self):
????????"""
????????運(yùn)行程序
????????:return:
????????"""
????????data?=?spider.crawl_data()??#?運(yùn)行爬取
????????if?len(data)?>?0:??#?如果爬取到的數(shù)據(jù)不為空
????????????self.concat_and_write_data(data)
????????????start?=?str(datetime.fromtimestamp(self.starttime))[:10]
????????????end?=?str(datetime.fromtimestamp(self.endtime))[:10]
????????????print(f'{start}至{end}數(shù)據(jù)爬取任務(wù)完成')
????def?pivot_data(self):
????????"""
????????將數(shù)據(jù)轉(zhuǎn)換為透視表式的格式
????????:return:
????????"""
????????data?=?self.data.copy()
????????data['年月']?=?data['日期'].map(lambda?x:?f'{str(x)[:7]}')
????????data['日']?=?data['日期'].map(lambda?x:?x.day)
????????data?=?data.pivot_table(values='收盤',?index='日',?columns='年月',?aggfunc='sum')
????????data_mean?=?data.mean().to_frame().T
????????data_mean.index?=?['平均值']
????????data?=?pd.concat([data,?data_mean])
????????data.to_excel(self.data_file.parent.parent?/?'data.xlsx',?encoding='utf-8')
if?__name__?==?'__main__':
????spider?=?Spider()
????spider.run()
????spider.pivot_data()
????print(spider.data)
總結(jié)
??從技術(shù)角度來看,經(jīng)過一步步解析,任務(wù)是簡單的,入門requests爬蟲以及入門pandas數(shù)據(jù)分析就可以完成(唯一的難度在找到合適的目標(biāo))。但是換個(gè)角度,從經(jīng)濟(jì)價(jià)值來看,又是很有價(jià)值的,即節(jié)約了某網(wǎng)站高昂的年費(fèi)(注:并不是說年費(fèi)不值得,只是局限在需求僅僅是CU2206一項(xiàng)數(shù)據(jù)上時(shí),性價(jià)比太低),同時(shí)又避免了人工操作的繁瑣,以及可能產(chǎn)生的錯(cuò)誤。用很小的學(xué)習(xí)成本就能解決大大的問題,所以,還等什么呢?開啟Python之路吧!
關(guān)注我的抖音賬號(hào):Python導(dǎo)師-螞蟻
每晚21點(diǎn)直播,給你講解副業(yè)、Python學(xué)習(xí)路線;

