我曾经做过这样的事情。这太可怕了,但它确实有效。
您需要添加对Microsoft.mshtml 的引用。
然后你可以使用IHTMLDocument2。为什么是2?好问题......无论如何,我写了几个这样的辅助函数:
public static void FillField(object doc, string id, string value)
{
var element = findElementByID(doc, id);
element.setAttribute("value", value);
}
public static void ClickButton(object doc, string id)
{
var element = findElementByID(doc, id);
element.click();
}
private static IHTMLElement findElementByID(object doc, string id)
{
IHTMLDocument2 thisDoc;
if (!(doc is IHTMLDocument2))
return null;
else
thisDoc = (IHTMLDocument2)doc;
var element = thisDoc.all.OfType<IHTMLElement>()
.Where(n => n != null && n.id != null)
.Where(e => e.id == id).First();
return element;
}
执行JS
private static void ExecuteScript(object doc, string js)
{
IHTMLDocument2 thisDoc;
if (!(doc is IHTMLDocument2))
return;
else
thisDoc = (IHTMLDocument2)doc;
thisDoc.parentWindow.execScript(js);
}
我这样称呼他们...
HtmlDocumentHelper.FillField(webBrowser.Document, <id>, <value>);
HtmlDocumentHelper.FillField(webBrowser.Document, <id>, <value>);
HtmlDocumentHelper.ClickButton(webBrowser.Document, <id>);
HtmlDocumentHelper.ExecuteScript(webBrowser.Document, "alert(1);");