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

使用C#与HtmlAgilityPack获取网页中的iframe代码

使用C# + HtmlAgilityPack提取指定区域的iframe代码

没问题,这个需求用HtmlAgilityPack实现起来很简单,我给你写个完整的控制台程序示例,一步到位解决你的问题:

第一步:安装HtmlAgilityPack

首先得确保你的项目里安装了这个包,有几种方式:

  • 打开Visual Studio的NuGet包管理器,搜索HtmlAgilityPack并安装
  • 用Package Manager Console执行命令:
    Install-Package HtmlAgilityPack
  • 或者用.NET CLI命令:
    dotnet add package HtmlAgilityPack

第二步:完整代码实现

下面是控制台程序的完整代码,包含了直接加载HTML字符串和从网页加载两种场景的处理:

using HtmlAgilityPack;
using System;

namespace IframeExtractorDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            // 场景1:你已经有了目标HTML内容(比如从网页爬取到的字符串)
            string localHtml = @"<div class=""playercont""> <div id=""singlePlay"" class=""dp_player"" data-o="" "" data-s="" ""> <p><iframe src=""video.com/sadas"" scrolling=""no"" frameborder=""0"" width=""640"" height=""360"" allowfullscreen=""true"" webkitallowfullscreen=""true"" mozallowfullscreen=""true""></iframe></p> </div> </div>";
            
            // 初始化HTML文档并加载内容
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(localHtml);

            // 场景2:如果要直接从目标网站加载HTML,替换上面两行为下面的代码
            // HtmlWeb web = new HtmlWeb();
            // HtmlDocument doc = web.Load("你的目标网站完整URL");

            // 用XPath定位目标iframe:先找到class为playercont的div,再递归查找内部的iframe
            HtmlNode targetIframe = doc.DocumentNode.SelectSingleNode("//div[@class='playercont']//iframe");

            if (targetIframe != null)
            {
                // 提取完整的iframe标签代码
                string fullIframeCode = targetIframe.OuterHtml;
                Console.WriteLine("提取到的完整iframe代码:");
                Console.WriteLine(fullIframeCode);

                // 如果你需要单独获取src属性的值,用下面的代码
                string iframeSrc = targetIframe.GetAttributeValue("src", "未找到src属性");
                Console.WriteLine("\niframe的src地址:");
                Console.WriteLine(iframeSrc);
            }
            else
            {
                Console.WriteLine("未找到目标iframe,请检查HTML结构或XPath表达式是否正确");
            }

            Console.WriteLine("\n按任意键退出...");
            Console.ReadKey();
        }
    }
}

关键代码说明

  • XPath定位://div[@class='playercont']//iframe这个表达式会先找到所有class为playercont的div,然后递归查找这些div内部的所有iframe,不管iframe嵌套在多少层子元素里都能命中。
  • 获取完整HTML:OuterHtml属性会返回整个iframe标签的完整代码,这正是你需要的结果。
  • 属性提取:GetAttributeValue方法是安全获取属性的方式,第二个参数是当属性不存在时返回的默认值,避免空引用异常。

运行这个程序,就能直接看到你要的iframe代码啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:32:34