You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#使用HtmlAgilityPack获取加密货币实时价始终返回首次值如何解决

问题修复方案

核心原因

  • WebClient默认启用本地请求缓存,相同URL的重复请求会优先读取首次拉取的本地缓存,不会发起新的网络请求获取最新页面内容
  • 目标站点对缺省标准请求头的请求会返回固定缓存内容,不会返回实时更新的页面数据

修复后的代码

private void button1_Click(object sender, EventArgs e)
{
    timer1.Start();
}

private void timer1_Tick(object sender, EventArgs e)
{
    Uri url = new Uri("https://www.bloomberght.com/borsa");
    WebClient client = new WebClient();
    // 禁用WebClient缓存
    client.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
    // 添加标准浏览器请求头,避免站点返回缓存内容
    client.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
    client.Encoding = System.Text.Encoding.UTF8;
    string html = client.DownloadString(url);
    HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
    document.LoadHtml(html);
    HtmlNodeCollection nodes = document.DocumentNode.SelectNodes("//a[@id='dolar']/span[@class='data-info']/small[@data-type='son_fiyat']");

    foreach (var item in nodes)
    {
        label1.Text = item.InnerText;
        listBox1.Items.Add(item.InnerText);
    }
    // 释放WebClient资源避免内存泄漏
    client.Dispose();
}

额外优化建议

  • 可以用HttpClient替代WebClient,HttpClient是.NET官方推荐的更高效的HTTP请求类,支持连接复用,性能更好
  • 建议对网络请求添加异常捕获逻辑,避免请求失败导致程序崩溃

内容的提问来源于stack exchange,提问作者Enes Mindiloğlu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 15:00:04