[Excel] [VBA] VBA 인터넷 프로그래밍

Internet Explorer 개체

 

#
 
Set createInternetExplorerObject = CreateObject("InternetExplorer.Application")

도구> 참조> Microsoft 인터넷 컨트롤
관련 DLL : ieframe.dll
출처 : Internet Explorer 브라우저

MSDN-InternetExplorer 개체

자동화를 통해 Windows Internet Explorer의 인스턴스를 제어합니다.

 

Internet Explorer Objec 기본 멤버#

아래 코드는 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>

다음과 같은 코드를 사용하여 정보를 얻고 설정할 수 있습니다.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

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

 

Microsoft HTML Object Library 또는 IE 가장 친한 친구#

IE에로드되는 HTML을 최대한 활용하려면 Microsoft HTML Object Library 와 같은 다른 라이브러리를 사용할 수 있습니다. 다른 예에서 이것에 대해 더 자세히.

 

IE 주요 문제#

IE의 주된 문제는 페이지가로드되고 상호 작용할 준비가되었는지 확인하는 것입니다. Do While... Loop 도움이되지만 신뢰할 수 없습니다.

또한 IE를 사용하여 HTML 컨텐트를 긁어내는 것은 OVERKILL입니다. 왜? 브라우저는 모든 CSS, 자바 스크립트, 그림, 팝업 등으로 웹 페이지를 검색하는 것을 의미하기 때문에 원시 데이터 만 필요하면 다른 접근 방법을 고려하십시오. 예 : XML HTTP 요청을 사용 합니다 . 다른 예에서 이것에 대해 더 자세히.

 
 

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
858 (엑셀vba)EncodeUrl, DecodeUrl 졸리운_곰 2019.12.27 96
» [Excel] [VBA] VBA 인터넷 프로그래밍 file 졸리운_곰 2019.12.27 721
856 Perl과 한글 file 졸리운_곰 2019.12.25 138
855 짱! 한글 (한글언어) 자연어처리 Awesome-Korean-NLP 졸리운_곰 2019.12.24 499
854 2시간 반만에 펄 익히기 : become perl programmer by only 2 hours! 졸리운_곰 2019.12.24 83
853 온라인 업무 진행을 위한 기획서 목차 졸리운_곰 2019.12.19 79
852 웹기획 절차 / 기획서 목차 졸리운_곰 2019.12.19 77
851 표준 제안서 목차 졸리운_곰 2019.12.12 76
850 IT 제안서 작성 프로세스와 기법 file 졸리운_곰 2019.12.12 117
849 NLP 참고 인터넷 문서 정리 [자연어처리] [한글 자연언어처리] 졸리운_곰 2019.12.11 2224
848 아마존 클라우드 사용법 file 졸리운_곰 2019.12.11 202
847 Aws GPU 인스턴스를 이용해 딥러닝 환경 구축하기 file 졸리운_곰 2019.12.11 155
846 BlockChain: An extremely basic example of BlockChain in Excel - VBA file 졸리운_곰 2019.11.23 65
845 Eclipse Public License 2.0 졸리운_곰 2019.11.18 80
844 [SCORE] Eclipse Public License 1.0 졸리운_곰 2019.11.18 334
843 Top 10 Trending Artificial Intelligence Frameworks and Libraries file 졸리운_곰 2019.11.18 185
842 CYC 프로젝트 : 고대인의 인공지능 프로젝트 졸리운_곰 2019.11.15 98
841 Windows 환경에서 port forwarding 구현하기 file 졸리운_곰 2019.11.06 82
840 윈도우 포트포워딩을 이용한 사설 네트워크 접속 file 졸리운_곰 2019.11.06 103
839 Windows에서 포트 포워딩(Port Forwarding) 설정하기 - Netsh 졸리운_곰 2019.11.06 311
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED