1. 获取frame的名字,解决方法:
HTMLDocument doc =(HTMLDocument)webBrowser1.Document.DomDocument;
object j;
for (int i = 0; i< doc.parentWindow.frames.length; i++)
{
j = i;
HTMLWindow2Classframe = doc.parentWindow.frames.item(ref j) as HTMLWindow2Class;
string name =frame.name;
}
找到frame后就可以获取源文件了
string frameHtml =webBrowser1.Document.Window.Frames["mainFrame"].Document.Body.InnerHtml;
2. 有些网页中的新跳转页面是通过click事件来控制跳转的,如果直接获取StatusText的值是获取不了url的,它会直接返回“完成”,解决方法:
在【webBrowser1_DocumentCompleted】注册事件里添加如下代码
System.Windows.Forms.HtmlElementhtml = webBrowser1.Document.CreateElement("div");
html.InnerHtml+= "<a id=\"popLink\" href=\"\"target=\"_blank\"style=\"display:none;\"></a>";
webBrowser1.Document.Body.AppendChild(html);
stringjsHtml = "";
jsHtml+= "window.open=function(url,title,prop)";
jsHtml+= "{";
jsHtml+= "obj=document.getElementById('popLink');";
jsHtml+= "obj.style.display='block';";
jsHtml+= "obj.href=url;";
jsHtml+= "obj.focus();";
jsHtml+= "obj.click();";
jsHtml+= "obj.style.display='none'";
jsHtml+= "}";
mshtml.IHTMLDocument2doc = webBrowser1.Document.DomDocument as mshtml.IHTMLDocument2;
mshtml.IHTMLWindow2win = doc.parentWindow as mshtml.IHTMLWindow2;
win.execScript(jsHtml,"javascript");
3. 有些网页会用IFrame去嵌套别的页面,这些页面就可能不在相同域名下,这时就出现跨域问题了,解决方法:
1) 首先添加引用Interop.SHDocVw.dll(网上下载)、Microsoft.mshtml(系统自带)
2) 新写类
public class CrossFrameIE
{
public static IHTMLDocument2 GetDocumentFromWindow(IHTMLWindow2 htmlWindow)
{
if (htmlWindow == null)
{
return null;
}
try
{
IHTMLDocument2 doc = htmlWindow.document;
return doc;
}
catch (COMException comEx)
{
if (comEx.ErrorCode != E_ACCESSDENIED)
{
return null;
}
}
catch (System.UnauthorizedAccessException)
{
}
catch
{
return null;
}
try
{
IServiceProvider sp = (IServiceProvider)htmlWindow;
object brws = null;
sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out brws);
SHDocVw.IWebBrowser2 browser = (SHDocVw.IWebBrowser2)(brws);
return (IHTMLDocument2)browser.Document;
}
catch
{
}
return null;
}
private const int E_ACCESSDENIED = unchecked((int)0x80070005L);
private static Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
private static Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11D0-8A3E-00C04FC9E26E");
}
[ComImport(), ComVisible(true), Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IServiceProvider
{
[return: MarshalAs(UnmanagedType.I4)]
[PreserveSig]
int QueryService(ref Guid guidService, ref Guid riid, [MarshalAs(UnmanagedType.Interface)]out object ppvObject);
}
3) 使用
IHTMLWindow2 win = (IHTMLWindow2)webBrowser1.Document.Window.Frames["iFrame_1"].DomWindow;//获取需要调用的Frame
IHTMLDocument2 doc = (IHTMLDocument2)CrossFrameIE.GetDocumentFromWindow(win);