我试图通过调用一个包含表单的站点,然后插入一些我已经知道的值来为我的客户自动化一个简单的过程。因此,用户只需要完成缺少的值并提交表单。到目前为止,我所做的是启动IE并导航到包含表单的站点。我甚至能够检索输入元素,但我无法找到为它们设置值的方法。如果我试图使用" value“作为属性/方法名来设置一个值,我只会收到"Description: 80004001 / name”。我被困在这里了。
通过使用c#和.NET,我可以通过执行以下操作来完成这一任务:
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。然而--使用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运行时成为强制性的,我试图避免这种情况。
谢谢,马丁
发布于 2014-12-07 19:48:35
尝试遍历文档对象,使用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");
}
}https://stackoverflow.com/questions/27346265
复制相似问题