首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 操作 Iframe:獲取/設置嵌套頁面 HTML 內容

     編輯:關於C#

場景

採集目標頁面內容位於多層 Iframe 中(如 Page > Iframe1 > Iframe2),需穿透層層獲取/修改內容。

工具

Spider Studio (GDT 采集工作站) + 內建 jQuery 風格選擇器 API。

關鍵 API

  • Default.SelectSingleNode(selector):選擇元素
  • .Contents():進入 Iframe 內部文檔
  • .Html() / .Text():獲取 HTML/文本
  • .Attr(name, value):設置屬性

實戰步驟

1. 獲取第一層 Iframe

var iframe1 = Default.SelectSingleNode("#result iframe").Contents().SelectSingleNode("body");
if (!iframe1.IsEmpty()) MessageBox.Show(iframe1.Html());

2. 獲取第二層 Iframe

var iframe2 = Default.SelectSingleNode("#result iframe")
    .Contents().SelectSingleNode("iframe")
    .Contents().SelectSingleNode("body");
if (!iframe2.IsEmpty()) MessageBox.Show(iframe2.Html());

3. 修改第二層 Iframe 的 src

var iframe2Elem = Default.SelectSingleNode("#result iframe").Contents().SelectSingleNode("iframe");
iframe2Elem.Attr("src", "https://www.gdtsearch.com"); // 頁面跳轉

跨域限制

若 Iframe 頁面與父頁面不同域,瀏覽器同源策略阻止訪問 .Contents(),會拋出安全異常。此為瀏覽器原生限制,無法繞過。

判斷 Iframe 加載完成

public void IFrameReady(JQueryContext iframe, string jqExpr) {
    while (Default.Available) {
        var contents = iframe.Contents();
        if (!contents.IsEmpty()) {
            var node = contents.SelectSingleNode(jqExpr);
            if (!node.IsEmpty() && node.Html().Trim().Length > 10) return;
        }
        Thread.Sleep(1000);
        Application.DoEvents();
    }
}

輪詢檢查目標選擇器是否可選中且內容非空。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved