如何在 WPF Webbrowser 中使用 C# 将字符串插入输入字段

How to insert string into input field using C# in WPF Webbrowser

我在 Whosebug 上找到了很多关于这个问题的信息,但看起来我还是遗漏了什么。使用Webbrowser,我想在某个网页的输入字段中填写一个字符串。通过单击按钮,我希望在输入字段中输入一些文本。

这是我的代码:

using System.Windows.Forms;

和函数:

    private void button2_Click(object sender, RoutedEventArgs e)
    {
        HtmlDocument doc = (HtmlDocument)webBrowser1.Document;
        doc.GetElementsByTagName("input")["username"].SetAttribute("Value", "someString");
    }

第二个按钮处理 webBbrowser1.Navigate 方法。

然后我得到这个错误:

{"Unable to cast COM object of type 'mshtml.HTMLDocumentClass' to class type 'System.Windows.Forms.HtmlDocument'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface."}

有什么想法吗?谢谢

错误发生在这一行:

HtmlDocument doc = (HtmlDocument)webBrowser1.Document;

看看thiswebBrowswer1.Document 在 WPF returns Microsoft.mshtml.HTMLDocuement 所以要么添加对 Microsoft.mshtml 的引用,然后:

private void button2_Click(object sender, RoutedEventArgs e)
{
    var doc = webBrowser1.Document as mshtml.HTMLDocument;
    var input = doc.getElementsByTagName("input");
    foreach (mshtml.IHTMLElement element in input)
    {
        if (element.getAttribute("name") == "username")
        {
            element.setAttribute("value", "someString");
            break;
        }
    }
}

private void button2_Click(object sender, RoutedEventArgs e)
{
    dynamic doc = webBrowser1.Document;
    dynamic input = doc.getElementsByTagName("input");
    foreach (dynamic element in input)
    {
        if (element.getAttribute("name") == "username")
        {
            element.setAttribute("value", "someString");
            break;
        }
    }
}

更多信息:

  • Find specific data in html with HtmlElement(Collection) and webbrowser