Files
squad-rain-ops-mini/Helpers/SteamCrawlerHelper.cs

84 lines
3.3 KiB
C#

using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
namespace RainOpsMini.Helpers
{
/// <summary>
/// Steam爬虫助手类
/// </summary>
public static class SteamCrawlerHelper
{
/// <summary>
/// 通过HTML解析查询Squad游戏时长和玩家昵称
/// </summary>
/// <param name="steamid">玩家SteamID</param>
/// <returns>包含游戏时长(小时)和昵称的元组</returns>
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. 获取昵称 <title>Steam Community :: Nickname</title>
var titleMatch = Regex.Match(htmlContent, @"<title>Steam Community :: (.*?)</title>", RegexOptions.IgnoreCase);
if (titleMatch.Success)
{
nickname = titleMatch.Groups[1].Value.Trim();
}
// 2. 解析游戏时长
var result = new Dictionary<string, double>();
string pattern = @"<div\s+class=""game_name""><a[^>]*href=""https://steamcommunity\.com/app/(\d+)"">(.*?)</a></div>.*?<div\s+class=""game_info_details"">[^<]*总时数\s*([\d,]+)\s*小时";
string patternEn = @"<div\s+class=""game_name""><a[^>]*href=""https://steamcommunity\.com/app/(\d+)"">(.*?)</a></div>.*?<div\s+class=""game_info_details"">[^<]*([\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, "");
}
}
}