-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHTMLParser.cpp
More file actions
425 lines (343 loc) · 10.2 KB
/
HTMLParser.cpp
File metadata and controls
425 lines (343 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
/*
Code taken from project https://github.com/ClaudiuHBann/Web_Scraper_v2
Need some functionality? Hit me up or Fork it :P
*/
#include <Mshtml.h>
#include <atlstr.h>
#include <io.h>
#include <fcntl.h>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
thread_local size_t HTMLParserInstanceCount = 0;
class HTMLParser
{
public:
HTMLParser()
{
if (!HTMLParserInstanceCount++)
{
auto result = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
if (result != S_OK && result != S_FALSE && result != RPC_E_CHANGED_MODE)
{
HTMLParserInstanceCount--;
}
}
}
~HTMLParser()
{
Uninitialize7();
Uninitialize3();
Uninitialize2();
if (!--HTMLParserInstanceCount)
{
CoUninitialize();
}
}
IHTMLDocument2 *GetIHTMLDocument2()
{
Initialize2();
return mIHTMLDocument2;
}
IHTMLDocument3 *GetIHTMLDocument3()
{
Initialize3();
return mIHTMLDocument3;
}
IHTMLDocument7 *GetIHTMLDocument7()
{
Initialize7();
return mIHTMLDocument7;
}
bool Parse(const wstring &html)
{
if (!Initialize2())
{
return false;
}
CString htmlCString(html.c_str());
auto safeArray = SafeArrayCreateVector(VT_VARIANT, 0, 1);
if (!safeArray)
{
return false;
}
VARIANT *variant{};
auto result = SafeArrayAccessData(safeArray, (void **)&variant);
if (!variant)
{
SafeArrayDestroy(safeArray);
return false;
}
variant->vt = VT_BSTR;
variant->bstrVal = htmlCString.AllocSysString();
result = mIHTMLDocument2->write(safeArray);
mIHTMLDocument2->close();
SysFreeString(variant->bstrVal);
SafeArrayDestroy(safeArray);
return SUCCEEDED(result);
}
static inline IHTMLElementCollection *GetElementAllAsCollection(IHTMLElement *element)
{
if (!element)
{
return nullptr;
}
IDispatch *childrenRaw{};
auto result = element->get_all(&childrenRaw);
if (FAILED(result))
{
return nullptr;
}
IHTMLElementCollection *children{};
result = childrenRaw->QueryInterface(IID_IHTMLElementCollection, reinterpret_cast<void **>(&children));
return children;
}
static inline IHTMLElement *GetElementFromCollectionByIndex(IHTMLElementCollection *collection, const long index)
{
if (!collection)
{
return nullptr;
}
VARIANT variantName{};
variantName.vt = VT_UINT;
variantName.lVal = index;
VARIANT variantIndex{};
variantIndex.vt = VT_I4;
variantIndex.intVal = 0;
IDispatch *iDispatch{};
auto result = collection->item(variantName, variantIndex, &iDispatch);
if (!iDispatch)
{
return nullptr;
}
IHTMLElement *element{};
result = iDispatch->QueryInterface(IID_IHTMLElement, (void **)&element);
return element;
}
static inline bool ElementHasAttribute(IHTMLElement *element, const pair<wstring, wstring> &attribute)
{
return GetElementAttributeValueByName(element, attribute.first) == attribute.second;
}
static bool ElementHasAttributes(IHTMLElement *element, const vector<pair<wstring, wstring>> &attributes)
{
if (!element)
{
return false;
}
for (const auto &attribute : attributes)
{
if (!ElementHasAttribute(element, attribute))
{
return false;
}
}
return true;
}
inline wstring GetScriptAsString(const long index)
{
IHTMLElementCollection *scripts{};
GetIHTMLDocument2()->get_scripts(&scripts);
if (!scripts)
{
return {};
}
auto script = GetElementFromCollectionByIndex(scripts, index);
if (!script)
{
return {};
}
return GetElementInnerHTML(script);
}
static inline wstring GetElementInnerHTML(IHTMLElement *element)
{
if (!element)
{
return {};
}
BSTR bstr;
element->get_innerHTML(&bstr);
return bstr ? bstr : wstring();
}
static inline wstring GetElementInnerText(IHTMLElement *element)
{
if (!element)
{
return {};
}
BSTR bstr;
element->get_innerText(&bstr);
return bstr ? bstr : wstring();
}
inline IHTMLElement *GetElementById(const wstring &id)
{
BSTR bStr = SysAllocString(id.c_str());
IHTMLElement *element{};
GetIHTMLDocument3()->getElementById(bStr, &element);
SysFreeString(bStr);
return element;
}
inline vector<IHTMLElement *> GetElementsByAttributes(const vector<pair<wstring, wstring>> &attributes)
{
IHTMLElementCollection *collection{};
auto result = GetIHTMLDocument2()->get_all(&collection);
if (FAILED(result))
{
return {};
}
return GetCollectionElementsByAttributes(collection, attributes);
}
static vector<IHTMLElement *> GetCollectionElementsByAttributes(IHTMLElementCollection *collection,
const vector<pair<wstring, wstring>> &attributes)
{
if (!collection)
{
return {};
}
vector<IHTMLElement *> htmlElements{};
long collectionLength;
collection->get_length(&collectionLength);
for (long i = 0; i < collectionLength; i++)
{
auto element = GetElementFromCollectionByIndex(collection, i);
if (element && ElementHasAttributes(element, attributes))
{
htmlElements.push_back(element);
}
}
return htmlElements;
}
inline IHTMLElementCollection *GetElementsByClassName(const wstring &name)
{
BSTR bStr = SysAllocString(name.c_str());
IHTMLElementCollection *collection{};
GetIHTMLDocument7()->getElementsByClassName(bStr, &collection);
SysFreeString(bStr);
return collection;
}
static inline wstring GetElementAttributeValueByName(IHTMLElement *element, const wstring &name)
{
if (!element)
{
return {};
}
VARIANT variantAttribute{};
variantAttribute.vt = VT_BSTR;
CString attributeNameCString(name.c_str());
auto attributeNameBStr = attributeNameCString.AllocSysString();
auto result = element->getAttribute(attributeNameBStr, 0, &variantAttribute);
SysFreeString(attributeNameBStr);
if (SUCCEEDED(result) && variantAttribute.vt == VT_BSTR && variantAttribute.bstrVal)
{
return variantAttribute.bstrVal;
}
else
{
return {};
}
}
private:
IHTMLDocument2 *mIHTMLDocument2{};
IHTMLDocument3 *mIHTMLDocument3{};
IHTMLDocument7 *mIHTMLDocument7{};
inline bool Initialize2()
{
if (!HTMLParserInstanceCount)
{
return false;
}
if (mIHTMLDocument2)
{
return true;
}
return SUCCEEDED(CoCreateInstance(CLSID_HTMLDocument, nullptr, CLSCTX_INPROC_SERVER, IID_IHTMLDocument2,
(void **)&mIHTMLDocument2));
}
inline bool Uninitialize2()
{
if (!mIHTMLDocument2)
{
return true;
}
return !mIHTMLDocument2->Release();
}
inline bool Initialize3()
{
if (!Initialize2())
{
return false;
}
if (mIHTMLDocument3)
{
return true;
}
return SUCCEEDED(mIHTMLDocument2->QueryInterface(IID_IHTMLDocument3, (void **)&mIHTMLDocument3));
}
inline bool Uninitialize3()
{
if (!mIHTMLDocument3)
{
return true;
}
return !mIHTMLDocument3->Release();
}
inline bool Initialize7()
{
if (!Initialize2())
{
return false;
}
if (mIHTMLDocument7)
{
return true;
}
return SUCCEEDED(mIHTMLDocument2->QueryInterface(IID_IHTMLDocument7, (void **)&mIHTMLDocument7));
}
inline bool Uninitialize7()
{
if (!mIHTMLDocument7)
{
return true;
}
return !mIHTMLDocument7->Release();
}
};
#include <winrt/windows.foundation.h>
#include <winrt/windows.web.http.h>
using namespace winrt;
using namespace Windows;
using namespace Foundation;
using namespace Web::Http;
int main()
{
auto &&_ = _setmode(_fileno(stdout), _O_U16TEXT);
_;
Uri uri(L"https://github.com/ClaudiuHBann/Web_Scraper_v2");
HttpClient client;
auto &&html = client.GetStringAsync(uri).get();
HTMLParser parser;
parser.Parse(html.data());
auto elementByID = parser.GetElementById(L"fork-button");
wcout << format(L"Element with ID: {} has HTML: {}", L"fork-button", HTMLParser::GetElementInnerHTML(elementByID))
<< endl;
wcout << format(L"Element with ID: {} has Text: {}", L"fork-button", HTMLParser::GetElementInnerText(elementByID))
<< endl
<< endl;
auto elements = parser.GetElementsByAttributes({{L"type", L"button"}});
for (auto element : elements)
{
auto &&elementText = HTMLParser::GetElementInnerText(element);
if (!elementText.empty())
{
wcout << format(LR"(Button with attribute {}="{}" has text: {})", L"type", L"button", elementText) << endl;
}
auto elementChildren = HTMLParser::GetElementAllAsCollection(element);
long elementChildrenCount;
elementChildren->get_length(&elementChildrenCount);
wcout << format(LR"(Button with attribute {}="{}" has {} children)", L"type", L"button", elementChildrenCount)
<< endl;
}
wcout << endl;
wcout << format(L"Script 1:\n{}", parser.GetScriptAsString(0)) << endl;
return 0;
}