当我尝试访问此内容时:
var anchors = webBrowser1.Document.Window.Frames[0].Document.GetElementsByTagName("a");
我收到未经授权的访问异常。到底是怎么回事!?我可以在抛出异常时在对象浏览器中查看整个文档,我也可以在 webBrowser1 内手动单击此 iframe,但是当我尝试在应用程序内访问它时,我收到错误?这是什么妖术?
这是因为浏览器不允许您从另一个域访问 iframe,这种情况也会发生在域名相同的 https 网站上,幸运的是有一种方法可以解决这个问题。
页面完全加载后,您可以使用 JS 获取 IFrame 的内容。
首先加载嵌入了 iframe 的页面的 url:
webBrowser1.Navigate("https://www.example.com/pagecontaingiframe.html");
webBrowser1.DocumentCompleted += WebBrowserDocumentCompleted;
然后在文档完成事件中,检查 iframe url 是否已加载,而不是我们导航到的原始 url,加载后,使用eval
javascript 中的函数来运行我们自己的代码来提取 iframe 的内容。
void WebBrowserDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Optionally check that the url is the original document
// search for an iframe and its url here first.
// Then store the name and url for the next step
// And the magic begins
if (e.Url.AbsolutePath != new Uri("https://www.example.com/iframeyouneedurl.html").AbsolutePath)
return;
webBrowser1.DocumentCompleted -= WebBrowserDocumentCompleted;
string jCode = "var iframe = document.getElementsByName('iframe_element')[0]; var innerDoc = iframe.contentDocument || iframe.contentWindow.document; innerDoc.documentElement.innerHTML";
string html = webBrowser1.Document.InvokeScript("eval", new object[] { jCode });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)