반응형

C# -- IE automation #6 -- 구글 검색창 제어하기


참고 : https://msdn.microsoft.com/ko-kr/library/aa752541(v=vs.85).aspx  --> IHTMLDocument3 interface

       https://msdn.microsoft.com/ko-kr/library/aa703928(v=vs.85).aspx  --> IHTMLElementCollection interface  -- item

       http://www.csharpstudy.com/Practical/Prac-IE.aspx 

       http://blog.clockahead.com/2015/06/cie-8.html



부제 :  HTML 태그 속성 제어하기

    - setAttribute() 사용법 익히기

- 버튼 클릭하기.



<< 미션 >>

internet explorer (IE) 에서 구글 검새창을 연후에, 검색어에 "푸들" 입력하고 클릭버튼 눌러서 검색 결과 확인하기.




** IE 8 에서는 id 없어서 name 으로 구글 검색 박스 찾고, IE 11 에서는 id 표시되어 id 로 검색 입력박스 찾는다.

   ( 우연히 발견함... but, IE 9, IE 10 은 안해봐서 모름.....)


using System;
namespace IE_ex2
{
class Program
{
static void Main(string[] args)
{
test1();
test2();
Console.ReadLine(); // Enter 입력해야 다음으로 넘아감.
}
// id 로 구글검색창 찾아, 단어입력후 click 하여 검색하기...
static void test1()
{
var IE = new SHDocVw.InternetExplorer();
IE.Visible = true;
Object URL = "http://www.google.com/";
IE.Navigate2(ref URL);
IE.Wait(); // 페이지의 요소를 반영하기 위해서는 페이지가 표시 될 때까지 기다릴 필요
var doc = IE.Document as mshtml.IHTMLDocument3;
if (doc.getElementById("lst-ib") == null)
{
// IE8 에서는 구글검색창 id 없음. -- 실패!!!
// IE 11 에서는 성공!!!
Console.WriteLine(" .. 현재 버전의 IE 에서는 해당 id 요소 없음.......");
return;
}
doc.getElementById("lst-ib").innerText = "푸들"; // id = lst-ib 검색 상자
doc.getElementsByName("btnK").item(index: 0).click(); // 버튼 클릭하기.
}
// name 으로 구글검색창 찾아, 단어입력후 click 하여 검색하기...
static void test2()
{
var IE = new SHDocVw.InternetExplorer();
IE.Visible = true;
Object URL = "http://www.google.com/";
IE.Navigate2(ref URL);
IE.Wait(); // 페이지의 요소를 반영하기 위해서는 페이지가 표시 될 때까지 기다릴 필요
var doc = IE.Document as mshtml.IHTMLDocument3;
mshtml.IHTMLElement q = doc.getElementsByName("q").item("q", 0);
if (q != null)
{
q.setAttribute("value", "푸들");
doc.getElementsByName("btnG").item(index: 0).click(); // 버튼 클릭하기.
}
else
{
Console.WriteLine("\n\n ... q 없음........");
}
}
}
// 페이지 로딩 완료까지 대기하는 확장 메서드
public static class SHDovVwEx
{
public static void Wait(this SHDocVw.InternetExplorer ie, int millisecond = 0)
{
while (ie.Busy == true || ie.ReadyState != SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE)
{
System.Threading.Thread.Sleep(100);
}
System.Threading.Thread.Sleep(millisecond);
}
}
}
view raw IE_ex2.cs hosted with ❤ by GitHub



** 소스 52번째 줄은 3가지 방법중 하나로 대신할수 있다.


var doc = IE.Document as mshtml.IHTMLDocument3;


// ----- 아래 3가지 방법 모두 가능...

mshtml.IHTMLElement q = doc.getElementsByName("q").item("q", 0);

// mshtml.IHTMLElement q = doc.getElementsByName("q").item(index:0);

// mshtml.IHTMLElement q = doc.getElementsByName("q").item(Type.Missing, 0);





반응형
Posted by 자유프로그램
,