InvokeMember(“click”) webBrowser help

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

I am trying to automate a web page via the weBrowser and the button that i'm trying to click has no ID only a value. here's the html code for it:

 

I can't useGetElementById as the button has no ID. If I do

HtmlElement goButton = this.webBrowser1.Document.All["Accept"]; goButton.InvokeMember("click"); 

My script stops showing a nullreference error highlighting the "goButton.InvokeMember("click");"

If I do

var inputControls = (from HtmlElement element in webBrowser1.Document.GetElementsByTagName("input") select element).ToList();             HtmlElement submitButton = inputControls.First(x => x.Name == "Accept"); 

My script give me an "Sequence contains no matching element" error at the "HtmlElement submitButton" line and sometimes the page has more than one of these Accept buttons, so I would need to be able to tell the difference between each one as well or at least be able to click on one without the script breaking

Any help with this will be greatly appreciated

回答1:

You're trying to find a button tag, correct? If that's the case, GetElementsByTagName("input") probably should be GetElementsByTagName("button"). The Name of the button isn't going to be Accept either, that'll be the InnerText property. If you're not sure that the button exists, you're probably better off using FirstOrDefault and checking for a null return value, as '.First' will crash and burn if there's no match.

As for how you can tell the difference between the buttons if there's more than one Accept button, I think that one needs a bit more thought.

This code is untested, but it might be closer to what you need

var buttonControls = (     from HtmlElement element      in webBrowser1.Document.GetElementsByTagName("button")      select element ).ToList();  HtmlElement submitButton =      buttonControls.FirstOrDefault(x => x.InnerText == "Accept");  if (submitButton != null) {     submitButton.InvokeMember("click"); } else {     //didn't find it } 


回答2:

Looks like there is no matching element in the page. Are you sure the button is on the current page, not in an embedded frame?

Anyway you need to have error checking. NullReferenceException should not be intentionally raised.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!