using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text.RegularExpressions; namespace RainOpsMini.Helpers { /// /// Steam爬虫助手类 /// public static class SteamCrawlerHelper { /// /// 通过HTML解析查询Squad游戏时长和玩家昵称 /// /// 玩家SteamID /// 包含游戏时长(小时)和昵称的元组 public static (int Hours, string Nickname) GetHtmlSquadRunTime(string steamid) { try { string url = "https://steamcommunity.com/profiles/" + steamid + "/"; string htmlContent = ""; using (WebClient myWebClient = new WebClient()) { // 添加User-Agent myWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"); myWebClient.Encoding = System.Text.Encoding.UTF8; htmlContent = myWebClient.DownloadString(url); } if (string.IsNullOrEmpty(htmlContent)) return (0, ""); string nickname = ""; // 1. 获取昵称 Steam Community :: Nickname var titleMatch = Regex.Match(htmlContent, @"Steam Community :: (.*?)", RegexOptions.IgnoreCase); if (titleMatch.Success) { nickname = titleMatch.Groups[1].Value.Trim(); } // 2. 解析游戏时长 var result = new Dictionary(); string pattern = @"]*href=""https://steamcommunity\.com/app/(\d+)"">(.*?).*?[^<]*总时数\s*([\d,]+)\s*小时"; string patternEn = @"]*href=""https://steamcommunity\.com/app/(\d+)"">(.*?).*?[^<]*([\d,]+)\s+hrs"; var matches = Regex.Matches(htmlContent, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase); if (matches.Count == 0) { matches = Regex.Matches(htmlContent, patternEn, RegexOptions.Singleline | RegexOptions.IgnoreCase); } foreach (Match match in matches) { if (match.Groups.Count >= 3) { string gameName = match.Groups[2].Value.Trim(); string hoursStr = match.Groups[3].Value.Replace(",", ""); if (double.TryParse(hoursStr, out double hours)) { result[gameName] = hours; } } } if (result.ContainsKey("Squad")) { return ((int)result["Squad"], nickname); } } catch (Exception ex) { RainOpsLog.Log($"[Steam爬虫助手] 解析异常 ({steamid}): {ex.Message}"); } return (0, ""); } } }