반응형

C# -- IE automation #3 -- internet explorer 제어하여 html 소스 가져오기


환경 : windows 7 64bit, visual studio 2013 community 


참고 : http://stackoverflow.com/questions/14780981/how-to-view-source-html-from-an-internetexplorer-object/14781171#14781171

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

       


1. Internet explorer 를 제어하기 위해서는 SHDocVw 참조 필요하고, HTML 제어위해 MSHTML 참조 필요함.


SHDocVw -- Microsoft Internet Controls

MSHTML -- Microsoft HTML Object Library




2. References 에 MSHTML, SHDocVw 2가지 모두 추가됨.




3. Program.cs 의 소스

  --- http://example.com/ 같은 간단한 페이지는 잘 출력되지만, 네이버처럼 페이지 로딩시간 긴것은 에러 발생하는 문제 발생한다.


using System;
namespace IEtest2
{
class Program
{
static void Main(string[] args)
{
SHDocVw.InternetExplorer IE = new SHDocVw.InternetExplorer();
// object Empty = 0;
object Empty = new object();
dynamic url = "http://www.naver.com/";
// object url = "http://example.com/";
IE.Visible = true;
IE.Navigate2(ref url, ref Empty, ref Empty, ref Empty, ref Empty);
// html 로딩되기전에 html document 접근하면, 에러발생...
// --- www.naver.com 접근시에는 에러 발생한다.
try
{
mshtml.HTMLDocument doc = IE.Document;
Console.WriteLine("doc.title == " + doc.title);
Console.WriteLine("doc.URL == " + doc.url);
Console.WriteLine("-------------------------------\n\n");
Console.Write(doc.body.parentElement.outerHTML); // 모든 html 보여주기
}
catch (Exception e)
{
Console.WriteLine("================ error ================");
Console.WriteLine("{0}", e); // 에러 표시
}
Console.ReadLine();
}
}
}
view raw IEtest2.cs hosted with ❤ by GitHub







<< 해결방안 >>


-- 해당 페이지 로딩이 완료될때까지 기다린후, html 을 읽어들인다.



위의 소스 19번 줄의

   IE.Navigate2(ref url, ref Empty, ref Empty, ref Empty, ref Empty);


은 아래와 같이 간단하게 해도된다.

   IE.Navigate2(ref url);  // 간단한 표현




using System;
namespace IETest3
{
class Program
{
static void Main(string[] args)
{
SHDocVw.InternetExplorer IE = new SHDocVw.InternetExplorer();
// object Empty = 0;
object Empty = new object();
dynamic url = "http://www.naver.com/";
// object url = "http://example.com/";
IE.Visible = true;
// IE.Navigate2(ref url, ref Empty, ref Empty, ref Empty, ref Empty);
IE.Navigate2(ref url); // 간단한 표현
// 페이지 로딩이 완료될때까지 기다림....
while (IE.Busy == true || IE.ReadyState != SHDocVw.tagREADYSTATE.READYSTATE_COMPLETE)
{
System.Threading.Thread.Sleep(100);
}
mshtml.HTMLDocument doc = IE.Document;
Console.WriteLine("doc.title == " + doc.title);
Console.WriteLine("doc.URL == " + doc.url);
Console.WriteLine(" -------------------------------\n\n");
Console.Write(doc.body.parentElement.outerHTML); // 모든 html 보여주기
Console.ReadLine();
}
}
}
view raw IEtest3.cs hosted with ❤ by GitHub




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