publicstringGetSeasonReportUrl(EnumModels.SeasonReportType seasonReportType) { switch (seasonReportType) { case EnumModels.SeasonReportType.綜合損益表: return"https://mops.twse.com.tw/mops/web/ajax_t163sb04"; case EnumModels.SeasonReportType.資產負債表: return"https://mops.twse.com.tw/mops/web/ajax_t163sb05"; default: thrownew ArgumentException($"{seasonReportType.ToString()} Url 不存在"); } }
爬蟲部分
希望透過傳入參數的方式,就可以取得某一季的財報,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
publicasync Task<string> ReadSeasonReportHtmlByTWSEAsync(EnumModels.SeasonReportType seasonReportType, int year, int season) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded")); var response = await client.PostAsync( GetSeasonReportUrl(seasonReportType), new StringContent($"encodeURIComponent=1&step=1&firstin=1&off=1&isQuery=Y&TYPEK=sii&year={year}&season={season}") ); var result = await response.Content.ReadAsStringAsync(); if (response.StatusCode != System.Net.HttpStatusCode.OK) thrownew PlatformNotSupportedException($"目前無法爬取財報資料...,{response.StatusCode},{result}"); return result; } }
publicvoidInsert(IEnumerable<SeasonReport> seasionReportList) { try { using (var scope = new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 5, 0))) { foreach (var seasionReport in seasionReportList) { _conn.Insert(seasionReport); } scope.Complete(); } } catch (Exception ex) { _logger.LogError(ex.Message); } }
publicintGetMaxYear(EnumModels.SeasonReportType seasonReportType) { return _conn.ExecuteScalar<int>( "select isnull(max(year), 106) from SeasonReport where type=@type", new { type = ((int)seasonReportType) } ); }
publicintGetMaxSeason(EnumModels.SeasonReportType seasonReportType, int year) { return _conn.ExecuteScalar<int>( "select isnull(max(season), 1) from SeasonReport where year=@year and type=@type", new { year, type = ((int)seasonReportType) } ); }
publicboolIsExist(EnumModels.SeasonReportType seasonReportType, int year, int season) { return _conn.ExecuteScalar<bool>( "select count(1) from SeasonReport where year=@year and season=@season and type=@type", new { year, season, type = ((int)seasonReportType) } ); } }