c# 控制IE瀏覽器

來源:互聯網
上載者:User
想寫一個傳統型程式,用C#。
程式運行後,會用IE開啟指定的網頁,並自動登入網站,再根據需要進行一些操作。
關鍵是不知道怎麼控制IE瀏覽器,請大家指點一下。

相關內容如下:

C#控制IE瀏覽器
引入 C:\WINDOWS\System32\mshtml.tlb、Interop.SHDocVw.dll

/// <summary>
/// 返回指定Url的IE視窗下的 IHTMLDocument2 對象。
/// </summary>
/// <returns>IHTMLDocument2</returns>
public static IHTMLDocument2 GetIHTMLDocument2ByUrl(string url)
{
SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindowsClass();
foreach (SHDocVw.InternetExplorer ie in shellWindows)
{
string filename = System.IO.Path.GetFileNameWithoutExtension(ie.FullName).ToLower();
if (filename.Equals(“iexplore“) && ie.LocationURL == url)
{
return ie.Document as IHTMLDocument2;
}
}
}

通過 GetIHTMLDocument2ByUrl 方法可以擷取已開啟的IE視窗中指寫地址的視窗中的 IHTMLDocument2 對象。
利用這個對象,就可以進行相關操作。
1.填寫表單
IHTMLDocument2 iHTMLDocument2 = GetIHTMLDocument2ByUrl(“http://www.163.com“);
IHTMLInputElement input = (IHTMLInputElement)iHTMLDocument2.all.item(“Username“, 0); // 擷取指定名稱的對象
input.value = “Xiao“; // 賦值

2.點擊按鈕
IHTMLDocument2 iHTMLDocument2 = GetIHTMLDocument2ByUrl(“http://www.163.com“);
HTMLDocumentClass obj = (HTMLDocumentClass)iHTMLDocument2;
IHTMLElement iHTMLElement = null;
IHTMLElementCollection c = obj.getElementsByTagName(“input“);
foreach (IHTMLElement e in c)
{
if (e.outerHTML.IndexOf(“登入“) != -1)
{
iHTMLElement = e;
break;
}
}
if (iHTMLElement != null)
{
iHTMLElement.click(); // 點擊登入按鈕
}

更多功能可以參考 IHTMLDocument2 對象。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.