不一致的原因是什么 - HTMLInputElement mshtml
我的要求 - 我以编程方式打开 Internet Explorer 的实例。然后,我获取 HTMLDocument 并查找输入字段(文本框),然后设置其值。
HTMLDocument oDoc = new mshtml.HTMLDocumentClass();
oDoc = (HTMLDocument)oBrowser.Document;
HTMLInputElement txtbox1 = (HTMLInputElement)oDoc.all.item("login",0);
txtbox1.setAttribute("value", "test_user_name", 0);
//txtbox1.value = "test_user_name";
我的代码工作正常,直到查找输入字段。问题出在我上面发布的代码中的某个地方。我获取 HTMLDocument 对象,然后查找名为“login”的 HTMLInputElement。在这里,我遇到了不一致的情况 - 有时无法识别文本框,因此当它到达 txtbox1.SetAttribute
或 txtbox1.value
时,会出现 NullReferenceException
被抛出。但是,这种情况并不总是发生。有时,不会引发异常,代码也可以正常工作。 我尝试过通过代码进行调试,但是当我通过代码进行调试时,错误从未出现!
我无法找出原因是什么?是什么原因导致这种不一致呢?有什么想法吗?
My requirement - I open an instance of Internet Explorer programmatically. Then, I get the HTMLDocument and look for an input field(textbox) and then set its value.
HTMLDocument oDoc = new mshtml.HTMLDocumentClass();
oDoc = (HTMLDocument)oBrowser.Document;
HTMLInputElement txtbox1 = (HTMLInputElement)oDoc.all.item("login",0);
txtbox1.setAttribute("value", "test_user_name", 0);
//txtbox1.value = "test_user_name";
My code works fine untill the input field is looked for. The problem is somewhere in the code I ahve posted above. I obtain the HTMLDocument object, then I look for the HTMLInputElement with the name "login". Here, I face an inconsistency - The text box is not recognised sometimes and so when it reaches the txtbox1.SetAttribute
or txtbox1.value
then a NullReferenceException
is thrown. But, this doesn't happen always. Sometimes the exception is not thrown and the code works just fine.
I have tried debugging through the code, but the error never shows up when I debug through the code!!
I am unable to find out what the reason can be? What causes this inconsistency? Any Ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您确定代码运行时页面已完全加载吗?如果不是,则执行代码时 DOM 可能不包含您的控件。
您应该添加一个 webBrowser1.DocumentCompleted 事件,然后在完成的事件处理程序中执行代码以确保 DOM 已完全创建。
我还建议使用 System.Windows.Forms 中的 WebBrowser 控件,而不是 axwebbrowser 和 mshtml。也就是说,如果您将浏览器托管在您自己的窗口中。我过去遇到过一些关于 mshtml 的问题,尤其是与事件挂钩相关的问题。
Are you certain the page is fully loaded when your code runs? If not, the DOM might not include your control at the time you execute your code.
You should add a webBrowser1.DocumentCompleted event and then execute your code in the completed event handler to make sure the DOM is fully created.
I would also recommend using the WebBrowser control from System.Windows.Forms instead of axwebbrowser and mshtml. That is if you are hosting the browser in a window of your own. I've experienced some issues with mshtml in the past, especially related to hooking on events.