Parsing html in vba

How to Web Scrape with VBA using IE & Parse HTML?

Web scraping is the process of extracting data available to public.

For example: You might want to extract stock historic data from a website to Excel in your computer. This way it is easy to analyse the stocks & decide on your Market activities.

It is unfair to use it to steal data from other websites & use it for you or sell it in open market.

Lets use it for better purpose.

VBA code to initiate IE & Extract a Website Data

The VBA code in this page can be run from a Excel VBA Editor.

  • It creates a object for Internet Explorer (IE).
  • Then navigates to the URL passed a parameter.
  • Once the page is loaded, it extracts the HTML data from IE.
  • Then use VBA commands to parse HTML elements.

Here is the actual code that does the above steps.

'-------------------------------------------------------------------------------- 'Code by officeticks123@gmail.com 'Visit https://officetricks.com to get more Free & Fully Functional VBA Codes '-------------------------------------------------------------------------------- Public Sub Web_Scrape_IE(sURL As String) 'Declare variables for IE Object & HTML file Dim objIE As Object, sHtml As HTMLDocument 'Create Internet Explorer Object Set objIE = CreateObject("InternetExplorer.Application") objIE.Visible = True 'Start navigate to Website URL objIE.navigate sURL Application.Wait DateAdd("s", 1, Now) 'Wait till Page loads Do While objIE.busy Application.StatusBar = "Application Loading. Please Wait. " Application.Wait DateAdd("s", 1, Now) DoEvents Loop 'Page loaded - Now Get the Website HTML Content Application.StatusBar = "Extracting Details" DoEvents Set sHtml = objIE.document 'Parse HTML Data from the website Set t0 = sHtml.getElementsByClassName("Classname") 'Loop thru each Parsed Element For Each t1 In t0 'Parse Sub Elements t3 = t1.getElementsByTagName("h2") For Each t4 In t3 'Display parsed element from HTML MsgBox t3.innertext Next Next 'Other Possible Parsing Functions 'sHtml.getElementById 'sHtml.getElementsByClassName 'sHtml.getElementsByTagName("a") 'sHtml.getAttribute("title") 'sHtml.parentElement.NextSibling 'Quit Internet Explorer objIE.Quit Set objIE = Nothing End Sub

This is pretty much the conceptual steps involved in most Web scraping tools. But just that the other technologies use Chrome & Firefox.

Читайте также:  Html table padding cells

Be it any technology or browser, the challenging part in most cases for a programmer is to decide on the HTML parsing & dealing with pagination concepts.

In many cases, CAPTCHA provides a good technique to step some beginner level web scrapers.

This code is not only used for web scraping or extracting web data. It can also be used to Automate some of the web activities like form filling, contacting website admin or support team, testing quiz etc.,

Источник

VBA Excel. Парсинг сайтов, html-страниц и файлов

Пользовательская функция GetHTML1 (VBA Excel) для извлечения (парсинга) текстового содержимого из html-страницы сайта по ее URL-адресу с помощью объекта «msxml2.xmlhttp»:

Парсинг сайтов (WinHttp.WinHttpRequest.5.1)

Парсинг файлов (ADODB.Stream)

Примеры записи текста в переменную

Извлечение данных из html

В понятие «парсинг», кроме извлечения текстового содержимого сайтов, html-страниц или файлов, входит поиск и извлечение конкретных данных из всего полученного текстового содержимого. Пример извлечения email-адресов из текста, присвоенного переменной, смотрите в последнем параграфе статьи: Регулярные выражения (объекты, свойства, методы).

Парсинг содержимого тегов

Парсинг содержимого Id

Для реализации представленных здесь примеров могут понадобиться дополнительные библиотеки. В настоящее время у меня подключены следующие (к данной теме могут относиться последние шесть):

  • Visual Basic For Applications
  • Microsoft Excel 16.0 Object Library
  • OLE Automation
  • Microsoft Office 16.0 Object Library
  • Microsoft Forms 2.0 Object Library
  • Ref Edit Control
  • Microsoft Scripting Runtime
  • Microsoft Word 16.0 Object Library
  • Microsoft Windows Common Controls 6.0 (SP6)
  • Microsoft ActiveX Data Objects 6.1 Library
  • Microsoft ActiveX Data Objects Recordset 6.0 Library
  • Microsoft HTML Object Library
  • Microsoft Internet Controls
  • Microsoft Shell Controls And Automation
  • Microsoft XML, v6.0

С этим набором библиотек все примеры работают. Тестирование проводилось в VBA Excel 2016.

6 комментариев для “VBA Excel. Парсинг сайтов, html-страниц и файлов”

Доброго дня, коллеги.
Задача следующая: в элементе ВэбБраузерКонтрол на странице поиска выполняю определенный запрос и визуально убедившись в получении нужного результата начинаю парсить содержимое. Вопрос как получить текстовое содержимое элемента ВэбБраузерКонтрол в момент когда там отображена нужная информация.
Заранее спасибо.

Доброго дня!
При попытке вычислить к примеру первое вхождение, ищет все равно следующее почему то. Sub Primer1()
Dim myHtml As String, myFile As Object, myTag As Object, myTxt As String
‘Извлекаем содержимое html-страницы в переменную myHtml с помощью функции GetHTML1
myHtml = GetHTML1(«https://bik-info.ru?040702802»)
‘Создаем объект HTMLFile
Set myFile = CreateObject(«HTMLFile»)
‘Записываем в myFile текст из myHtml
myFile.body.innerHTML = myHtml
‘Присваиваем переменной myTag коллекцию одноименных тегов, имя которого
‘указанно в качестве аргумента метода getElementsByTagName
Set myTag = myFile.getElementsByTagName(«strong»)
‘Выбираем, содержимое какого тега по порядку, начинающегося с 0, нужно извлечь
myTxt = myTag(0).innerText
Debug.Print myTxt
‘Большой текст может не уместиться в MsgBox, тогда для просмотра используйте окно Immediate
‘Debug.Print myTxt
End Sub Function GetHTML1(ByVal myURL As String) As String
On Error Resume Next
With CreateObject(«msxml2.xmlhttp»)
.Open «GET», myURL, False
.send
Do: DoEvents: Loop Until .readyState = 4
GetHTML1 = .responseText
End With
End Function

Здравствуйте, Сергей!
На HTML-странице, которую вы указали, тегом strong выделены только две одинаковые даты. Предположу, что отображается первая дата. Если strong заменить на b , отобразится знак $ , который идет первый с этим тегом.

Источник

Excel VBA html Table import – Export Web Table to Worksheet

Export HTML Table to Excel – When Web query does not work

To Import a HTML table in a web-page we can use,

  • Web Query option in Excel to import it to Excel or
  • From IE browser, right click on the Web Page Table & choose option “Export to Microsoft Excel“.

With some website this web query option will not work properly.

In that case, You can use this code to export HTML Table to Excel using VBA.

Excel VBA HTML Table Import – Step By Step

Extract the HTML Table content of the web page. The article in this page explains about how to import the HTML content.

  • In my Previous Article, the web page content is imported to Excel sheet as text content. But in this article, it is assigned to a HTMLFile Object which has more options to retrieve the HTML Tags.
  • Once you have the web page content, it will have the Table related Tags like , and .
  • Now the last step is to process each row & cell in that table and transfer it to the Excel Sheet.

VBA To Export HTML Table – Pull Website Table Data to Excel

Copy paste this code to Excel VB editor. Type web page URL that you want to scrape in cell A1 of worksheet1. Then

Sub Export_HTML_Table_To_Excel() Dim htm As Object Dim Tr As Object Dim Td As Object Dim Tab1 As Object 'Replace the URL of the webpage that you want to download Web_URL = VBA.Trim(Sheets(1).Cells(1, 1)) 'Create HTMLFile Object Set HTML_Content = CreateObject("htmlfile") 'Get the WebPage Content to HTMLFile Object With CreateObject("msxml2.xmlhttp") .Open "GET", Web_URL, False .send HTML_Content.Body.Innerhtml = .responseText End With Column_Num_To_Start = 1 iRow = 2 iCol = Column_Num_To_Start iTable = 0 'Loop Through Each Table and Download it to Excel in Proper Format For Each Tab1 In HTML_Content.getElementsByTagName("table") With HTML_Content.getElementsByTagName("table")(iTable) For Each Tr In .Rows For Each Td In Tr.Cells Sheets(1).Cells(iRow, iCol).Select Sheets(1).Cells(iRow, iCol) = Td.innerText iCol = iCol + 1 Next Td iCol = Column_Num_To_Start iRow = iRow + 1 Next Tr End With iTable = iTable + 1 iCol = Column_Num_To_Start iRow = iRow + 1 Next Tab1 MsgBox "Process Completed" End Sub

Press F5 to execute this code.

Excel will pull HTML table & align the content in the Excel sheet in proper format.

Limitations of Parsing HTML

In many of the Website, even including Facebook, Twitter, the webpage will look like tables.

But they are embedded inside its HTML DIV & SPAN tags and not the tag.

It is better to use Facebook, Twitter API rather than just relying on HTML tags.

Источник

Оцените статью