public class WebBrowserAssistant
{
System.Windows.Forms.WebBrowser wb;
public WebBrowserAssistant(System.Windows.Forms.WebBrowser wb) {
this.wb = wb;
}
public bool SetElementValue(string id,string value) {
this.wb.Document.GetElementById(id).SetAttribute("value", value);
return true;
} public object InvokeScript(string scriptName) {
return this.wb.Document.InvokeScript(scriptName);
}
public object InvokeScript(string scriptName,object[] ps)
{
return this.wb.Document.InvokeScript(scriptName, ps);
}
public void GetFocus(string id)
{
this.wb.Document.GetElementById(id).Focus();
}
public void GetBlur(string id)
{
this.wb.Document.GetElementById(id).RemoveFocus();
}
public string GetInputIDByName(string name)
{
return GetInputIDByName(name, name);
} public void ClickElement(string id) {
this.wb.Document.GetElementById(id).InvokeMember("click");
}
public string GetInputIDByName(string name,string id)
{
System.Windows.Forms.HtmlElementCollection es = this.wb.Document.GetElementsByTagName("input");
if (es != null && es.Count > ) {
System.Collections.IEnumerator ie = es.GetEnumerator();
System.Windows.Forms.HtmlElement e;
while (ie.MoveNext()) {
e = (System.Windows.Forms.HtmlElement)ie.Current;
if (e.Name.Equals(name))
{
if (string.IsNullOrEmpty(e.Id))
{
e.Id = id;
}
return e.Id;
}
}
}
return null;
} public List<string> GetEletemtByName(string name)
{
System.Windows.Forms.HtmlElementCollection es = this.wb.Document.GetElementsByTagName("input");
if (es != null && es.Count > )
{
List<string> result = new List<string>();
System.Collections.IEnumerator ie = es.GetEnumerator();
System.Windows.Forms.HtmlElement e;
while (ie.MoveNext())
{
e = (System.Windows.Forms.HtmlElement)ie.Current;
if (e.GetAttribute("type").Equals("checkbox") && e.Name.Equals(name) && e.GetAttribute("checked").Equals("True"))
{
result.Add(e.GetAttribute("value"));
}
}
return result;
}
return null;
}
public string ExeScript(string scriptBlock) {
return ExeScript(scriptBlock, "tempEletemtTagNameAndID");
}
public string ExeScript(string scriptBlock,string tempEletemtTagNameAndID) {
System.Windows.Forms.HtmlElement ele;
if (this.wb.Document.GetElementById(tempEletemtTagNameAndID) == null) {
ele = this.wb.Document.CreateElement(tempEletemtTagNameAndID);
ele.Id = tempEletemtTagNameAndID;
this.wb.Document.Body.AppendChild(ele);
}
ele = this.wb.Document.CreateElement("script");
ele.SetAttribute("type", "text/javascript"); ele.SetAttribute("text", string.Format("$j(\"#{0}\").val({1})", tempEletemtTagNameAndID, scriptBlock));
this.wb.Document.Body.AppendChild(ele); return this.wb.Document.GetElementById(tempEletemtTagNameAndID).GetAttribute("value");
} }
调用
MessageBox.Show(new Huawei.PortableComputer.Util.WebBrowserAssistant(this.wbTaskList).ExeScript("$j('.listContentTable td :checkbox:checked:first').parent().next().next().next().text()"));