Để điền dữ liệu vào textbox ta làm như sau:
- private void SetText(string elementId, WebBrowser webbrowser, string text)
- {
- HtmlElement element = webbrowser.Document.GetElementById(elementId);
- element.InnerText = text;
- }
- private void InvokeClick(string elementId,WebBrowser webbrowser)
- {
- HtmlElement element = webbrowser.Document.GetElementById(elementId);
- element.InvokeMember("click");
- }
Mình làm 1 ví dụ về chức năng tự động đăng nhập vào 1 trang web như sau:
- Đầu tiên tìm id của thẻ html nhập username. Ở đây mình giả sử là: txtUserName.
- Tìm id của thẻ html nhập password. Ở đây mình giả sử là txtPassword.
- Tìm id của button đăng nhập. Ở đây mình giả sử là btnLogin.
- // chuyển đến trang đăng nhập
- webBrowser1.Navigate("http://hanhtranglaptrinh.com/login.aspx");
- int timeOut = 5;
- DateTime start = DateTime.Now;
- DateTime now = DateTime.Now;
- // đợi load xong trang
- while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
- {
- Application.DoEvents();
- now = DateTime.Now;
- if ((now - start).TotalMinutes >= timeOut)
- {
- // làm cái gì đó
- throw new Exception("time out");
- }
- }
- // điền username
- SetText("txtUserName", webBrowser1, "admin");
- // điền pass
- SetText("txtPassword",webBrowser1,"123");
- // nhấn nút đăng nhập
- InvokeClick("btnLogin", webBrowser1);