[엑셀로 웹 스크래핑] Web Scraping - Basics

 

Web sites contains mass amount of data. Some times people need to extract those information for their needs. Web scraping is a popular technique use to collect data automatically from websites. Web scraping is also called as Web harvesting.

There are lot of uses of web scraping. It is used
  • To compare prices
  • To monitor weather data
  • To detect changes made to websites
  • For research purposes
  • To collect contact details
Complexity of the web scraping program depends on the web site and the data we going to collect. If we develop a web scraping software from VBA we need to use several in-built functions to make our program easier. Here below are very important functions we will need.

Functions helpful in web scraping

Mid - This function can be used to extract a string segment from it's parent string.
InStr - This function can be used to check whether certain string is included in another string and get the position of that sub string if it exists.
Replace - This function replace a character or string segments with another character or string.

Create an Internet Explorer object and navigate to a webpage

First, let's see how to create an internet explorer object. You can use below line of code to create that object.

Set objIE = CreateObject("InternetExplorer.Application")

Then set following attributes to the created object. You can change them according to your requirement. First to attributions decide the position of internet explorer window. Next to attributes will decide the size of the window.

objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600

Following attribute enable the viewing of window navigation. However you can set it to false if you do not want to see it.

objIE.Visible = True 

So now we have created the internet explorer object and set the attributes. Next let's see how to navigate to a website. You can use below line to navigate to the website you want.

objIE.Navigate ("http://www.example.com/")

There is a very important thing you need to know when developing a web scraping software. Your program will have to run through several line of codes after navigating to a specific website. However website can take some time to be fully loaded due to various reasons. So when you run the program there is a chance of running the rest of the code before web site is fully loaded. This can harmfully affected to the results you get from the software. However we can take preventive action to overcome this kind of situations. For that you need to always put below three lines where ever you have navigation command.

Do
DoEvents
Loop Until objIE.readystate = 4

Following is the full code you can use to Create an Internet Explorer object and navigate to a webpage.
 
Set objIE = CreateObject("InternetExplorer.Application")

objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600

objIE.Navigate ("http://www.example.com/")

Do
DoEvents
Loop Until objIE.readystate = 4

There is an another reason which can cause our program to behave differently to the way we have intended. There are times web sites not available due to different reasons. If our program try web harvest with a web site which is not online it will halt our program. So we need to use error handling techniques wisely to overcome this kind of scenarios.
Here below is a example of using error handling in VBA web scraping.
 

the_start:

Set objIE = CreateObject("InternetExplorer.Application")
objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600
objIE.Visible = True 'We will see the window navigation

On Error Resume Next
objIE.navigate ("http://www.example.com/")

Do
DoEvents
    If Err.Number <> 0 Then
        objIE.Quit
        Set objIE = Nothing
        GoTo the_start:
    End If
Loop Until objIE.readystate = 4

MsgBox "webpage has loaded"


Often we need to get the html code to a text box or to a variable, in first steps of the web scraping program. So here below is a code to paste html code of a specific web page to a text box.
Here txtHtml refers to a text box name.

txtHtml.Text = objIE.document.body.innerhtml

Some times it is very easier to get required data from the inner-text without dealing with html codes. So we can use below line of code to copy paste inner-text to a text box in that kind of situation.
txtHtml.Text = objIE.document.body.innertext

In web scraping, frequently we need to get elements by their tag names.
Here below is an example which can get elements have the "a" tags (anchor)

Set Alllinks = objIE.document.getelementsbytagname("A")
    For Each Hyperlink In Alllinks
        MsgBox Hyperlink.innertext & "-" & Hyperlink.href
    Next

Often web scraping software need to click links inside it's procedures.
Below example will click the link if it find a link with the text "New Arrivals"

Set Alllinks = objIE.document.getelementsbytagname("A")
    For Each Hyperlink In Alllinks
        If InStr(Hyperlink.innertext, "New Arrivals") > 0 Then
            Hyperlink.Click
            Exit For
        End If
    Next

Above are few basic things you need to know if you like to develop a software for Web scraping using VBA.

 

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

[출처] http://www.excelvbasolutions.com/2014/08/web-scraping.html

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
478 1조원 짜리 앱 아이디어 file 졸리운_곰 2016.12.05 198
477 Find and List all Files and Folders in a Directory file 졸리운_곰 2016.12.04 107
476 Rest Api 이해와 설계 및 개발 file 졸리운_곰 2016.11.28 270
475 우분투(Ubuntu) 서버 네트워크 설정 졸리운_곰 2016.11.26 85
474 말뫼(Malmo) 사용법 Tutorial file 졸리운_곰 2016.11.20 88
473 "마인크래프트로 AI 연구"…MS 오픈소스 프로젝트 공개 file 졸리운_곰 2016.11.20 126
472 마인크래프트 대체용 10가지 오픈소스 게임, 10 open source alternatives to Minecraft file 졸리운_곰 2016.11.13 274
471 App기획 [앱개발 프로세스] 졸리운_곰 2016.10.27 257
470 인공지능 기술자를 위한 파이썬 특강 (v0.2)의 사본.docx file 졸리운_곰 2016.10.27 142
469 프로그래밍 언어별 딥러닝 라이브러리 정리 file 졸리운_곰 2016.10.27 123
468 인공지능언어 프롤로그 프로그래밍 prolog.pdf file 졸리운_곰 2016.10.27 298
467 [엑셀로 웹 스크래핑3] Excel VBA Web Scraping Tutorial file 졸리운_곰 2016.10.09 302
466 [엑셀로 웹 스크래핑2] Scrape webpage data using Excel & VBA 졸리운_곰 2016.10.09 441
» [엑셀로 웹 스크래핑] Web Scraping - Basics 졸리운_곰 2016.10.09 374
464 Web Scraping Tutorial by ms excel 엑셀로 웹 스크래핑 file 졸리운_곰 2016.10.09 936
463 게임기획자를 위한 엑셀VBA 강좌 자료 파일 업로드 file 졸리운_곰 2016.10.03 129
462 마크다운에 관하여 file 졸리운_곰 2016.08.28 224
461 마크다운(Markdown)으로 글을 써보자 file 졸리운_곰 2016.08.28 225
460 Windows에서 텐서플로우 (tensorFlow)설치 file 졸리운_곰 2016.08.21 745
459 Top 50 open source web crawlers for data mining 졸리운_곰 2016.08.10 141
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED