一、获取网页源代码
1.不含有框架
string s=WB1.DocumentText; //webbrowser1命名为WB1,下同
2.含有框架
引用mshtml; //位置C:\Program Files\Microsoft.NET\Primary Interop Assemblies\Microsoft.mshtml.dll
object i_frame=0; //第一个框架IHTMLDocument2 doc = FWB.Document.DomDocument as IHTMLDocument2;
IHTMLFramesCollection2 frames = doc.frames as IHTMLFramesCollection2;
IHTMLWindow2 frame = frames.item(ref i_frame) as IHTMLWindow2;
IHTMLDocument2 frameDoc = frame.document as IHTMLDocument2;
string s=frameDoc.Document.body.innerHTML;
二、获取网页元素
1.根据ID
HtmlDocument ele= WB1.Document.getElementById("元素的ID");
2,根据name
HtmlDocument ele= WB1.Document.all["元素的name"];
3.无ID无Name----遍历元素
例如:<input type="submit">提交</input>
string str_temp;
HtmlDocument ele= WB1.Document.getElementById("元素的ID");
foreach (IHTMLElement ele in eles)
{
if (ele.getAttribute("type", 0) != null)
{
str_temp = ele.getAttribute("type", 0).ToString();
if (str_temp == "submit")
{
ele.click();
break;
}
}
}
三、遍历元素
HtmlDocument ele= WB1.Document.getElementById("元素的ID");
1.遍历所有元素
HtmlDocument doc = WB1.Document;
HtmlElementCollection elements = doc.All;
foreach (HtmlElement element in elements)
{
if (element.GetAttribute("type") == "submit")
{
element.InvokeMember("Click");
break;
}
}
2.根据元素类型 GetElementsByTagName
//目前有HTML、Form、Table、TR、TD、Div、A、 IMG、Li、Input、Span等
HtmlElementCollection eles = WB1.Document.GetElementsByTagName("li") as HtmlElementCollection;
foreach (HtmlElement ele in eles)
{
if (ele.InnerText != null)
{
if (ele.InnerText == "结婚饰品")
{
ele.InvokeMember("Click");
Application.DoEvents();
}
}
}
3.根据索引值
HtmlDocument ele= WB1.Document.getElementsByTagName("input")[0]; //获取input类型的第一个元素
4.根据上下节点和父节点
例如:
获取已知ID的下一个节点
HtmlDocument ele= WB1.Document.getElementById("元素的ID") .nextSibling; //上个节点 previousSibling
获取已知ID的父节点的第1个节点
HtmlDocument ele= WB1.Document.getElementById("元素的ID") .Parent.Children[0]; //或者firstChild
四、执行JS函数
1.用Navigate
WB1.Navigate("javascript:postComment();"); //postComment为要执行的JS函数
2.用IhtmlWindow2接口
IHTMLWindow2 win2 = WB1.Document.Window.DomWindow as IHTMLWindow2;
win2.execScript("function confirm(){return true;}", "javascript");
3.用IhtmlDocument2接口的parentWindow
IHTMLDocument2 doc2 = WB1.Document.DomDocument as IHTMLDocument2;
doc2.parentWindow.execScript("function confirm() {return true;}", "javascript");
待续