如何设置表单元素的值

时间:2014-12-07 18:33:33

标签: internet-explorer com

我尝试通过调用包含表单的网站为我的客户自动化一个简单的流程,然后插入一些我已经知道的值。因此,用户只需要填写缺失的值并提交表单。 到目前为止我所做的是启动IE并导航到包含表单的站点。 我甚至能够检索输入元素,但我找不到为它们设置值的方法。如果我尝试使用"值"设置值。作为属性/方法名称我只收到"描述:80004001 /未实现"。 我已经陷入困境。

在.NET中使用c#我可以通过执行以下操作来实现此目的:

SHDocVw.InternetExplorer IE = new SHDocVw.InternetExplorer();
IE.Navigate2("http://some.where");
var form = IE.Document.Forms(0);
form.Elements("foo").Value = "bar";
[...]
form.Submit();

但我不确定我是否通过这样做或某种特殊的.NET内容来使用COM。 但是 - 使用COM(来自java - 但我不认为这是相关的)我到目前为止这样做了:

ActiveXComponent xl = new ActiveXComponent("InternetExplorer.Application");
Dispatch ie = xl.getObject();
Dispatch.invoke(ie, "Navigate2", Dispatch.Method, new Object[] {"http://some.where"}, new int[1]);
// Now we're at http://some.where
xl.setProperty("Visible", new Variant(true));

// Getting the document
Dispatch document = Dispatch.get(ie, "Document").getDispatch();

// At this point I'm not able to call a property or method called "Elements"
// like I did with the c# example above. This makes me believe that my c#
// example is using a more 'integrated' IE-automation as the COM interface does.
// However, reading MSDN documentation I was a able to find a way to get a few sets further:

// Retrieving all input-elements
Dispatch elems = Dispatch.invoke(document, "getElementsByTagName", Dispatch.Method, new Object[] { "input" }, new int[1]).getDispatch();

// elems is now a pointer to a collection I can traverse
// To keep it simple I try to use the first element and do something with it:
Dispatch elem = Dispatch.invoke(elems, "item", Dispatch.Method, new Object[] { 0 }, new int[1]).getDispatch();

// 'elem' is now the first input-Element. To verify I can print out its name (foo):
System.out.println(Dispatch.get(elem, "name"));

// However - the following just fails with "Description: 80004001 / Not implemented".
Dispatch.invoke(elem, "value", Dispatch.Get, new Object[] { "test" }, new int[1]).getDispatch();

有没有办法通过COM界面操作HTML-Elements?如果它不是那么我需要用.NET包装那些东西并从我的代码中调用它,这使得客户端的.NET运行时是强制性的,我试图避免..

谢谢,马丁

1 个答案:

答案 0 :(得分:1)

尝试通过 Document 对象,使用 getElementsByTagName (或 getElementsById )找到元素,在html元素集合中循环并设置值使用 setAttribute ,指定属性

var docu = IE.Document; 
var htmlElements = docu.GetElementsByTagName("inputTagName");

foreach (HtmlElement htmlElement in htmlElements)
    {
        var name = htmlElement.GetAttribute("name");
        if (name != null && name.Length != 0)
        {
            htmlElement.SetAttribute("value","Test");
        }
    }