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

如何用C#捕获工业相机网页的网络请求以获取动态图片?

捕获工业相机网页动态图片的解决方案

方案1:解析页面HTML获取动态图片URL(最直接)

相机网页加载时会生成唯一的图片URL,可先请求基础页面,解析HTML提取图片地址后下载:

实现步骤

  • 用HttpClient请求相机基础URL,获取页面源码
  • 用HTML解析库提取图片标签的src属性
  • 处理相对URL为绝对地址,发起GET请求保存图片

代码示例

using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using HtmlAgilityPack;

class CameraImageCapture
{
    static async Task Main(string[] args)
    {
        string baseUrl = "http://你的相机本地IP";
        using var httpClient = new HttpClient();
        
        // 获取页面HTML
        var pageHtml = await httpClient.GetStringAsync(baseUrl);
        
        // 解析HTML定位图片元素(根据实际页面结构调整XPath)
        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(pageHtml);
        var imgNode = htmlDoc.DocumentNode.SelectSingleNode("//img[@src]"); 
        if (imgNode == null)
        {
            Console.WriteLine("未找到图片元素");
            return;
        }
        
        string imgUrl = imgNode.GetAttributeValue("src", "");
        if (string.IsNullOrEmpty(imgUrl))
        {
            Console.WriteLine("图片URL为空");
            return;
        }
        
        // 转换相对URL为绝对URL
        if (!Uri.IsWellFormedUriString(imgUrl, UriKind.Absolute))
        {
            imgUrl = new Uri(new Uri(baseUrl), imgUrl).ToString();
        }
        
        // 下载并保存图片
        var imgBytes = await httpClient.GetByteArrayAsync(imgUrl);
        string savePath = $"camera_image_{DateTime.Now:yyyyMMddHHmmss}.jpg";
        await File.WriteAllBytesAsync(savePath, imgBytes);
        
        Console.WriteLine($"图片已保存至: {savePath}");
    }
}

注意:需安装HtmlAgilityPack NuGet包,根据相机页面的DOM结构修改XPath表达式(比如指定图片的class或id)。

方案2:用本地代理拦截流量(替代FiddlerCore)

若解析HTML无效(比如图片URL由JS动态生成),可使用活跃维护的代理库ProxyKit拦截本地流量,捕获图片请求:

实现步骤

  • 启动本地HTTP代理
  • 配置浏览器使用该代理访问相机网页
  • 拦截GET请求,筛选图片类型请求并保存响应

代码示例

using System;
using System.Net;
using System.Threading.Tasks;
using ProxyKit;
using System.IO;

class ProxyImageCapture
{
    static async Task Main(string[] args)
    {
        var proxy = new Proxy();
        var listenAddress = new IPEndPoint(IPAddress.Loopback, 8888);
        
        // 添加拦截规则
        proxy.WhenForwarding
            .AddRule(async context =>
            {
                var request = context.HttpContext.Request;
                // 根据URL后缀或Content-Type筛选图片请求
                if (request.Method == "GET" && 
                    (request.Path.Value.EndsWith(".jpg") || request.Path.Value.EndsWith(".png")))
                {
                    // 转发请求并获取响应
                    var response = await context.ForwardToDestination();
                    
                    // 保存图片文件
                    string ext = Path.GetExtension(request.Path.Value);
                    string savePath = $"captured_image_{DateTime.Now:yyyyMMddHHmmss}{ext}";
                    using var stream = new FileStream(savePath, FileMode.Create);
                    await response.Content.CopyToAsync(stream);
                    
                    Console.WriteLine($"已捕获并保存图片: {savePath}");
                    return response;
                }
                return await context.ForwardToDestination();
            });
        
        // 启动代理
        await proxy.StartAsync(listenAddress);
        Console.WriteLine($"代理已启动在 {listenAddress}, 请将浏览器代理设置为127.0.0.1:8888,再访问相机网页");
        Console.WriteLine("按任意键停止代理...");
        Console.ReadKey();
        await proxy.StopAsync();
    }
}

注意:需安装ProxyKit NuGet包,运行后需手动设置浏览器代理。

方案3:用Selenium模拟浏览器(应对JS渲染场景)

如果图片URL是通过AJAX或JS动态生成的,可使用Selenium模拟浏览器加载页面,获取渲染后的图片地址:

实现步骤

  • 启动浏览器实例,导航到相机基础URL
  • 等待图片元素加载完成
  • 提取图片src属性并下载

代码示例

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.IO;
using OpenQA.Selenium.Support.UI;

class SeleniumImageCapture
{
    static async Task Main(string[] args)
    {
        string baseUrl = "http://你的相机本地IP";
        using var driver = new ChromeDriver();
        driver.Navigate().GoToUrl(baseUrl);
        
        // 等待图片加载(可根据实际情况调整等待条件)
        var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
        var imgElement = wait.Until(d => d.FindElement(By.TagName("img")));
        
        string imgUrl = imgElement.GetAttribute("src");
        if (string.IsNullOrEmpty(imgUrl))
        {
            Console.WriteLine("未获取到图片URL");
            return;
        }
        
        // 下载图片
        using var httpClient = new HttpClient();
        var imgBytes = await httpClient.GetByteArrayAsync(imgUrl);
        string savePath = $"selenium_image_{DateTime.Now:yyyyMMddHHmmss}.jpg";
        await File.WriteAllBytesAsync(savePath, imgBytes);
        
        Console.WriteLine($"图片已保存至: {savePath}");
        driver.Quit();
    }
}

注意:需安装Selenium.WebDriver NuGet包,并下载对应浏览器的驱动(如ChromeDriver),确保驱动与浏览器版本匹配。

内容的提问来源于stack exchange,提问作者Leon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 18:35:22