【问题标题】:how to set a value for form elements如何为表单元素设置值
【发布时间】:2015-02-05 09:59:19
【问题描述】:

我尝试通过调用一个包含表单的站点,然后插入一些我已经知道的值来为我的客户自动化一个简单的过程。因此,用户只需要填写缺失值并提交表单。 到目前为止我所做的是启动 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();

但我不确定我是否通过这样做来使用 COM 或某种具有更多可能性的特殊 .NET 东西。 但是 - 使用 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 元素吗?如果不是,那么我需要用 .NET 包装这些东西并从我的代码中调用它,这使得我试图避免在客户端强制使用 .NET 运行时..

谢谢,马丁

【问题讨论】:

    标签: internet-explorer com


    【解决方案1】:

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

    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");
            }
        }
    

    【讨论】:

    • 太棒了! “SetAttribute”就像一个魅力。谢谢!
    • 这个问题还在 IE 10 中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    • 2020-02-01
    • 2013-05-31
    • 2021-12-05
    相关资源
    最近更新 更多