c# - How to open web browser in a loop and enter data and wait until it fully loads -
i have c# form web browser control on it. want open url eg:(www. google.com)in loop , each time loop runs want first navigate url fill search string , click search button , wait until search results load fully.
how can this?
i wrote code save url after search result loads search result last string seems load , gets saved in list.
private void button1_click(object sender, eventargs e) { var task = donavigationasync(); task.continuewith((t) => { messagebox.show("done!"); }, taskscheduler.fromcurrentsynchronizationcontext()); } private void webbrowser1_documentcompleted(object sender, webbrowserdocumentcompletedeventargs e) { htmlelement url = webbrowser1.document.getelementbyid("sb_form_q"); if (url != null) { url.setattribute("value", search[searchindx-1]); webbrowser1.document.getelementbyid("sb_form_go").invokemember("click"); } if (webbrowser1.url.tostring() != "http://www.bing.com/") { savedurl.add(webbrowser1.url.tostring()); } } async task donavigationasync() { taskcompletionsource<bool> tcsnavigation = null; taskcompletionsource<bool> tcsdocument = null; this.webbrowser1.navigated += (s, e) => { if (tcsnavigation.task.iscompleted) return; tcsnavigation.setresult(true); }; this.webbrowser1.documentcompleted += (s, e) => { if (this.webbrowser1.readystate != webbrowserreadystate.complete) return; if (tcsdocument.task.iscompleted) return; tcsdocument.setresult(true); }; search = new string[3]; search[0] = "c"; search[1] = "c++"; search[2] = "c#"; searchindx = 0; foreach (string sval in search) { searchindx++; tcsnavigation = new taskcompletionsource<bool>(); tcsdocument = new taskcompletionsource<bool>(); webbrowser1.navigate("www.bing.com"); await tcsnavigation.task; await tcsdocument.task; } }
using async httpclient
.net framework 4.5, can load web page without using gui element such webbrowser
.
a download this:
using (httpclient client = new httpclient()) { await client.getstringasync("https://google.com"); }
this html content of google search site.
but if want have resulting url, won't need perform download because google (and other search engines) provides api that. note following google url: https://www.google.com/search?q=google
. can see search string "google" appears parameter named "q". if build code this...
string[] search = new string[] { "c", "c++", "c#" }; foreach (string sval in search) { // c# <= 5 savedurl.add(string.format("https://google.com/search?q={0}", sval)); // c# 6 savedurl.add($"https://google.com/search?q={sval}"); }
... won't need web access.
Comments
Post a Comment