[Excel] [VBA] VBA 인터넷 프로그래밍
2019.12.27 19:21
[Excel] [VBA] VBA 인터넷 프로그래밍
Internet Explorer 개체
Set createInternetExplorerObject = CreateObject("InternetExplorer.Application")
도구> 참조> Microsoft 인터넷 컨트롤
관련 DLL : ieframe.dll
출처 : Internet Explorer 브라우저
자동화를 통해 Windows Internet Explorer의 인스턴스를 제어합니다.
아래 코드는 IE 개체가 작동하는 방식과 VBA를 통해 IE 개체를 조작하는 방법을 소개합니다. 나는 그것을 통해 단계별 실행을 권장한다. 그렇지 않으면 다중 네비게이션 중에 오류가 발생할 수있다.
Sub IEGetToKnow()
Dim IE As InternetExplorer 'Reference to Microsoft Internet Controls
Set IE = New InternetExplorer
With IE
.Visible = True 'Sets or gets a value that indicates whether the object is visible or hidden.
'Navigation
.Navigate2 "http://www.example.com" 'Navigates the browser to a location that might not be expressed as a URL, such as a PIDL for an entity in the Windows Shell namespace.
Debug.Print .Busy 'Gets a value that indicates whether the object is engaged in a navigation or downloading operation.
Debug.Print .ReadyState 'Gets the ready state of the object.
.Navigate2 "http://www.example.com/2"
.GoBack 'Navigates backward one item in the history list
.GoForward 'Navigates forward one item in the history list.
.GoHome 'Navigates to the current home or start page.
.Stop 'Cancels a pending navigation or download, and stops dynamic page elements, such as background sounds and animations.
.Refresh 'Reloads the file that is currently displayed in the object.
Debug.Print .Silent 'Sets or gets a value that indicates whether the object can display dialog boxes.
Debug.Print .Type 'Gets the user type name of the contained document object.
Debug.Print .Top 'Sets or gets the coordinate of the top edge of the object.
Debug.Print .Left 'Sets or gets the coordinate of the left edge of the object.
Debug.Print .Height 'Sets or gets the height of the object.
Debug.Print .Width 'Sets or gets the width of the object.
End With
IE.Quit 'close the application window
End Sub
IE에서 가장 일반적으로하는 일은 웹 사이트의 일부 정보를 마킹하거나 웹 사이트 양식을 작성하고 정보를 제출하는 것입니다. 우리는 그것을하는 방법을 볼 것입니다.
example.com 소스 코드를 살펴 보겠습니다.
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style ... </style>
</head>
<body>
<div>
<h1>Example Domain</h1>
<p>This domain is established to be used for illustrative examples in documents. You may use this
domain in examples without prior coordination or asking for permission.</p>
<p><a href="http://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
다음과 같은 코드를 사용하여 정보를 얻고 설정할 수 있습니다.
Sub IEWebScrape1()
Dim IE As InternetExplorer 'Reference to Microsoft Internet Controls
Set IE = New InternetExplorer
With IE
.Visible = True
.Navigate2 "http://www.example.com"
'we add a loop to be sure the website is loaded and ready.
'Does not work consistently. Cannot be relied upon.
Do While .Busy = True Or .ReadyState <> READYSTATE_COMPLETE 'Equivalent = .ReadyState <> 4
' DoEvents - worth considering. Know implications before you use it.
Application.Wait (Now + TimeValue("00:00:01")) 'Wait 1 second, then check again.
Loop
'Print info in immediate window
With .Document 'the source code HTML "below" the displayed page.
Stop 'VBE Stop. Continue line by line to see what happens.
Debug.Print .GetElementsByTagName("title")(0).innerHtml 'prints "Example Domain"
Debug.Print .GetElementsByTagName("h1")(0).innerHtml 'prints "Example Domain"
Debug.Print .GetElementsByTagName("p")(0).innerHtml 'prints "This domain is established..."
Debug.Print .GetElementsByTagName("p")(1).innerHtml 'prints "<a href="http://www.iana.org/domains/example">More information...</a>"
Debug.Print .GetElementsByTagName("p")(1).innerText 'prints "More information..."
Debug.Print .GetElementsByTagName("a")(0).innerText 'prints "More information..."
'We can change the localy displayed website. Don't worry about breaking the site.
.GetElementsByTagName("title")(0).innerHtml = "Psst, scraping..."
.GetElementsByTagName("h1")(0).innerHtml = "Let me try something fishy." 'You have just changed the local HTML of the site.
.GetElementsByTagName("p")(0).innerHtml = "Lorem ipsum........... The End"
.GetElementsByTagName("a")(0).innerText = "iana.org"
End With '.document
.Quit 'close the application window
End With 'ie
End Sub
무슨 일 이니? 핵심 플레이어는 HTML 소스 코드 인 .Document 입니다. 우리는 우리가 원하는 컬렉션이나 객체를 얻기 위해 몇 가지 쿼리를 적용 할 수 있습니다.
예를 들어, IE.Document.GetElementsByTagName("title")(0).innerHtml . GetElementsByTagName 은 " title "태그가있는 HTML 요소의 컬렉션 을 반환합니다. 소스 코드에는 이러한 태그가 하나만 있습니다. Collection 은 0부터 시작합니다. 따라서 첫 번째 요소를 얻으려면 (0) 추가하십시오. 지금 우리의 경우 우리는 innerHtml (String)만을 원하고 Element Object 자체는 원하지 않습니다. 그래서 우리는 우리가 원하는 속성을 지정합니다.
사이트의 링크를 따라 가려면 여러 가지 방법을 사용할 수 있습니다.
Sub IEGoToPlaces()
Dim IE As InternetExplorer 'Reference to Microsoft Internet Controls
Set IE = New InternetExplorer
With IE
.Visible = True
.Navigate2 "http://www.example.com"
Stop 'VBE Stop. Continue line by line to see what happens.
'Click
.Document.GetElementsByTagName("a")(0).Click
Stop 'VBE Stop.
'Return Back
.GoBack
Stop 'VBE Stop.
'Navigate using the href attribute in the <a> tag, or "link"
.Navigate2 .Document.GetElementsByTagName("a")(0).href
Stop 'VBE Stop.
.Quit 'close the application window
End With
End Sub
IE에로드되는 HTML을 최대한 활용하려면 Microsoft HTML Object Library 와 같은 다른 라이브러리를 사용할 수 있습니다. 다른 예에서 이것에 대해 더 자세히.
IE의 주된 문제는 페이지가로드되고 상호 작용할 준비가되었는지 확인하는 것입니다. Do While... Loop 도움이되지만 신뢰할 수 없습니다.
또한 IE를 사용하여 HTML 컨텐트를 긁어내는 것은 OVERKILL입니다. 왜? 브라우저는 모든 CSS, 자바 스크립트, 그림, 팝업 등으로 웹 페이지를 검색하는 것을 의미하기 때문에 원시 데이터 만 필요하면 다른 접근 방법을 고려하십시오. 예 : XML HTTP 요청을 사용 합니다 . 다른 예에서 이것에 대해 더 자세히.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.


