Reputation: 987
For example, using code and no user input, how would I have my program click the "Search" button on google (assuming I've already filled in the search box and am at google.com)
Upvotes: 19
Views: 59510
Reputation: 1113
webBrowser1.Navigate("http://www.google.com");
If you have an ID
use this:
webBrowser1.Document.GetElementById("id").InvokeMember("click");
If you have TagName
use this
webBrowser1.Navigate("http://www.google.com");
In Web Browser DocumentCompleted event
HtmlElement textElement = webBrowser1.Document.All.GetElementsByName("q")[0];
textElement.SetAttribute("value", "your text to search");
HtmlElement btnElement = webBrowser1.Document.All.GetElementsByName("btnG")[0];
btnElement.InvokeMember("click");
If you have name Class
use this:
HtmlElementCollection classButton = webBrowser1.Document.All;
foreach (HtmlElement element in classButton)
{
if (element.GetAttribute("className") == "button")
{
element.InvokeMember("click");
}
}
For adding text in a TextBox
to search google.com, use this:
webBrowser1.Document.GetElementById("gs_tti0").InnerText = "hello world";
Upvotes: 44
Reputation: 341
In addition to using InvokeMember
and others, if your web page has issues responding when called by ID
or Class
, you can try using {TAB}
& {ENTER}
using the SendKeys
class within .NET. I've written a lot of scripts for web pages and have found that I've had to use a combination of both (even though SendKeys
is far messier than the methods in @AleWin's answer).
Here is the link to the SendKeys class.
Upvotes: 0
Reputation: 379
Try the following code:
public WebBrowser webBrowser1 = new WebBrowser();
private void WebForm_Load(object sender, EventArgs e)
{
try
{
webBrowser1.Height = 1000;
webBrowser1.Width = 1000;
this.Controls.Add(webBrowser1);
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
this.webBrowser1.Navigate("www.google.com.au");
}
catch
{ }
Write down the following function in your c# form:
public void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
var webBrowser = sender as WebBrowser;
webBrowser.DocumentCompleted -= WebBrowser_DocumentCompleted;
HtmlElement textElement = webBrowser.Document.All.GetElementsByName("q")[0];
textElement.SetAttribute("value", "mlm company");
HtmlElement btnElement = webBrowser.Document.All.GetElementsByName("btnG")[0];
btnElement.InvokeMember("click");
}
Upvotes: 2