-
Notifications
You must be signed in to change notification settings - Fork 5
/
scan.py
1661 lines (1370 loc) · 70 KB
/
scan.py
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
import argparse
import base64
import json
import multiprocessing as mp
import os
import subprocess
import traceback
from functools import partial
from multiprocessing import Lock
from urllib.parse import urlparse
import pychrome
import tld.exceptions
from abp.filters import parse_filterlist
from abp.filters.parser import Filter
from langdetect import detect
from tld import get_fld, get_tld
from tranco import Tranco
# Possible improvements:
# - if cookie notice is displayed in iframe (e.g. forbes.com), currently the
# iframe is assumed to be the cookie notice; one might even walk up the tree
# even further and find a fixed or full-width parent there
FAILED_REASON_TIMEOUT = 'Page.navigate timeout'
FAILED_REASON_STATUS_CODE = 'status code'
FAILED_REASON_LOADING = 'loading failed'
class Webpage:
def __init__(self, rank=None, domain='', protocol='https'):
self.rank = rank
self.domain = domain
self.protocol = protocol
self.url = f'{self.protocol}://{self.domain}'
def set_protocol(self, protocol):
self.protocol = protocol
self.url = f'{self.protocol}://{self.domain}'
def set_subdomain(self, subdomain):
self.url = f'{self.protocol}://{subdomain}.{self.domain}'
def remove_subdomain(self):
self.url = f'{self.protocol}://{self.domain}'
class WebpageResult:
def __init__(self, webpage):
self.rank = webpage.rank
self.domain = webpage.domain
self.tld = get_tld(webpage.url)
self.protocol = webpage.protocol
self.url = webpage.url
self.redirects = []
self.failed = False
self.failed_reason = None
self.failed_exception = None
self.failed_traceback = None
self.warnings = []
self.stopped_waiting = False
self.stopped_waiting_reason = None
self.requests = []
self.responses = []
self.cookies = {}
self.screenshots = {}
self.html = None
self.language = None
self.is_cmp_defined = False
self.cookie_notice_count = {}
self.cookie_notices = {}
self._json_excluded_fields = ['_json_excluded_fields', 'screenshots']
def add_redirect(self, url, root_frame=True):
self.redirects.append({
'url': url,
'root_frame': root_frame
})
def set_failed(self, reason, exception=None, traceback=None):
self.failed = True
self.failed_reason = reason
self.failed_exception = exception
self.failed_traceback = traceback
def add_warning(self, warning):
self.warnings.append(warning)
def set_stopped_waiting(self, reason):
self.stopped_waiting = True
self.stopped_waiting_reason = reason
def add_request(self, request_url):
self.requests.append({
'url': request_url,
})
def add_response(self, requested_url, status, mime_type, headers):
self.responses.append({
'url': requested_url,
'status': status,
'mime_type': mime_type,
'headers': headers,
})
def set_cookies(self, key, cookies):
self.cookies[key] = cookies
def add_screenshot(self, name, screenshot):
self.screenshots[name] = screenshot
def set_html(self, html):
self.html = html
def set_language(self, language):
self.language = language
def set_cmp_defined(self, is_cmp_defined):
self.is_cmp_defined = is_cmp_defined
def add_cookie_notices(self, detection_technique, cookie_notices):
self.cookie_notice_count[detection_technique] = len(cookie_notices)
self.cookie_notices[detection_technique] = cookie_notices
def save_screenshots(self, directory):
for name, screenshot in self.screenshots.items():
self._save_screenshot(name, screenshot, directory)
def _save_screenshot(self, name, screenshot, directory):
with open(f'{directory}/{self._get_filename_for_screenshot(name)}', 'wb') as file:
file.write(base64.b64decode(screenshot))
def _get_filename_for_screenshot(self, name):
return f'{self.rank}-{self.domain}-{name}.png'
def save_data(self, directory):
with open(f'{directory}/{self._get_filename_for_data()}', 'w', encoding='utf8') as file:
file.write(self._to_json())
def _get_filename_for_data(self):
return f'{self.rank}-{self.domain}.json'
def _to_json(self):
results = {k: v for k, v in self.__dict__.items() if k not in self._json_excluded_fields}
return json.dumps(results, indent=4, default=lambda o: o.__dict__, ensure_ascii=False)
def exclude_field_from_json(self, excluded_field):
self._json_excluded_fields.append(excluded_field)
class Click:
def __init__(self, detection_technique, cookie_notice_index, clickable_index):
self.detection_technique = detection_technique
self.cookie_notice_index = cookie_notice_index
self.clickable_index = clickable_index
class ClickResult:
def __init__(self):
self.cookies = {}
self.new_pages = []
self.cookie_notice_visible_after_click = None
self.is_page_modal = None
def set_cookies(self, key, cookies):
self.cookies[key] = cookies
def add_new_page(self, url, root_frame=True, new_window=False):
new_page = {
'url': url,
'root_frame': root_frame,
'new_window': new_window,
}
if new_page not in self.new_pages:
self.new_pages.append(new_page)
def has_new_pages(self):
return len(self.new_pages) > 0
def set_cookie_notice_visible_after_click(self, visible_after_click):
self.cookie_notice_visible_after_click = visible_after_click
def set_is_page_modal(self, is_page_modal):
self.is_page_modal = is_page_modal
class Browser:
def __init__(self, abp_filter_filenames, debugger_url='http://127.0.0.1:9222'):
# create a browser instance which controls chromium
self.browser = pychrome.Browser(url=debugger_url)
# create helpers
self.abp_filters = {
os.path.splitext(os.path.basename(abp_filter_filename))[0]: AdblockPlusFilter(abp_filter_filename)
for abp_filter_filename in abp_filter_filenames
}
def scan_page(self, webpage, do_click=False):
"""Tries to scan the webpage and returns the result of the scan.
Following possibilities are tried to scan the page:
- https protocol without `www.` subdomain
- https protocol with `www.` subdomain
- http protocol without `www.` subdomain
- http protocol with `www.` subdomain
The first scan whose result is not failed is returned.
"""
result = self._scan_page(webpage).get_result()
# try https with subdomain www
if result.failed and (result.failed_reason == FAILED_REASON_LOADING or result.failed_reason == FAILED_REASON_TIMEOUT):
webpage.set_subdomain('www')
result = self._scan_page(webpage).get_result()
# try http without subdomain www
if result.failed and (result.failed_reason == FAILED_REASON_LOADING or result.failed_reason == FAILED_REASON_TIMEOUT):
webpage.remove_subdomain()
webpage.set_protocol('http')
result = self._scan_page(webpage).get_result()
# try http with www subdomain
if result.failed and (result.failed_reason == FAILED_REASON_LOADING or result.failed_reason == FAILED_REASON_TIMEOUT):
webpage.set_subdomain('www')
result = self._scan_page(webpage).get_result()
if result.failed:
return result
# do the click and add the click results to the web page result
if do_click:
self.do_click(webpage, result)
return result
def do_click(self, webpage, result):
# store click results for nodes to avoid duplicates
click_results = {}
# click each element and add the click result to the webpage result
for detection_technique, cookie_notices in result.cookie_notices.items():
for cookie_notice_index, cookie_notice in enumerate(cookie_notices):
if len(cookie_notice.get('clickables')) > 5:
result.add_warning({
'message': 'Too many clickables to try them out',
'exception': 'TooManyClickables',
'method': 'Browser.do_click',
})
continue
for clickable_index, clickable in enumerate(cookie_notice.get('clickables')):
# check whether click was already done
if clickable.get('node_id') in click_results:
clickable['click_result'] = click_results.get(clickable.get('node_id'))
else:
# create click instruction
click = Click(detection_technique, cookie_notice_index, clickable_index)
# do click on web page
click_result = self._scan_page(webpage=webpage, take_screenshots=False, click=click).get_click_result()
# store results
clickable['click_result'] = click_result
click_results[clickable.get('node_id')] = click_result
def _scan_page(self, webpage, take_screenshots=True, click=None):
"""Creates tab, scans webpage and returns result."""
tab = self.browser.new_tab()
# scan the page
page_scanner = WebpageScanner(tab=tab, abp_filters=self.abp_filters, webpage=webpage)
page_scanner.scan(take_screenshots=take_screenshots, click=click)
# close tab and obtain the results
self.browser.close_tab(tab)
return page_scanner
class AdblockPlusFilter:
def __init__(self, rules_filename):
with open(rules_filename) as filterlist:
# we only need filters with type css
# other instances are Header, Metadata, etc.
# other type is url-pattern which is used to block script files
self._rules = [rule for rule in parse_filterlist(filterlist) if isinstance(rule, Filter) and rule.selector.get('type') == 'css']
def get_applicable_rules(self, domain):
"""Returns the rules of the filter that are applicable for the given domain."""
return [rule for rule in self._rules if self._is_rule_applicable(rule, domain)]
def _is_rule_applicable(self, rule, domain):
"""Tests whethere a given rule is applicable for the given domain."""
domain_options = [(key, value) for key, value in rule.options if key == 'domain']
if len(domain_options) == 0:
return True
# there is only one domain option
_, domains = domain_options[0]
# filter exclusion rules as they should be ignored:
# the cookie notices do exist, the ABP plugin is just not able
# to remove them correctly
domains = [(opt_domain, opt_applicable) for opt_domain, opt_applicable in domains if opt_applicable == True]
if len(domains) == 0:
return True
# the list of domains now only consists of domains for which the rule
# is applicable, we check for the domain and return False otherwise
for opt_domain, _ in domains:
if opt_domain in domain:
return True
return False
class WebpageScanner:
def __init__(self, tab, abp_filters, webpage):
self.tab = tab
self.abp_filters = abp_filters
self.webpage = webpage
self.result = WebpageResult(webpage)
self.click_result = ClickResult()
self.loaded_urls = []
def scan(self, take_screenshots=True, click=None):
self._setup()
try:
# open url and wait for load event and js
self._navigate_and_wait()
if self.result.failed:
return self.result
# get root node of document, is needed to be sure that the DOM is loaded
self.root_node = self.tab.DOM.getDocument().get('root')
# store html of page
self.result.set_html(self._get_html_of_node(self.root_node.get('nodeId')))
# detect language and cookie notices
self.detect_language()
self.detect_cookie_notices(take_screenshots=take_screenshots)
# get all cookies
self.result.set_cookies('all', self._get_all_cookies())
# do the click if necessary
self.do_click(click)
except Exception as e:
self.result.set_failed(str(e), type(e).__name__, traceback.format_exc())
# stop the browser from executing javascript
self.tab.Emulation.setScriptExecutionDisabled(value=True)
self.tab.wait(0.1)
try:
# clear the browser
self._clear_browser()
self.tab.wait(0.1)
except Exception as e:
print(type(e).__name__)
print(traceback.format_exc())
print(f'clearing browser failed ({self.webpage.url})')
# stop the tab
self.tab.stop()
def get_result(self):
return self.result
def get_click_result(self):
return self.click_result
############################################################################
# SETUP
############################################################################
def _setup(self):
# initialize `_is_loaded` variable to `False`
# it will be set to `True` when the `loadEventFired` event occurs
self._is_loaded = False
# data about requests/repsonses
self.recordRedirects = True
self.recordNewPagesForClick = False
self.waitForNavigatedEvent = False
self.requestId = None
self.frameId = None
# setup the tab
self._setup_tab()
self.tab.wait(0.1)
# deny permissions because they might pop-up and block detection
#self._deny_permissions() # problems with ubuntu
def _setup_tab(self):
# set callbacks for request and response logging
self.tab.Network.requestWillBeSent = self._event_request_will_be_sent
self.tab.Network.responseReceived = self._event_response_received
self.tab.Network.loadingFailed = self._event_loading_failed
self.tab.Page.loadEventFired = self._event_load_event_fired
self.tab.Page.frameRequestedNavigation = self._event_frame_requested_navigation
self.tab.Page.frameStartedLoading = self._event_frame_started_loading
self.tab.Page.navigatedWithinDocument = self._event_navigated_within_document
self.tab.Page.windowOpen = self._event_window_open
self.tab.Page.javascriptDialogOpening = self._event_javascript_dialog_opening
# start our tab after callbacks have been registered
self.tab.start()
# enable network notifications for all request/response so our
# callbacks actually receive some data
self.tab.Network.enable()
# enable page domain notifications so our load_event_fired
# callback is called when the page is loaded
self.tab.Page.enable()
# enable DOM, Runtime and Overlay
self.tab.DOM.enable()
self.tab.Runtime.enable()
self.tab.Overlay.enable()
def _navigate_and_wait(self):
try:
# open url
self._clear_browser()
#self.tab.Page.bringToFront()
self.tab.Page.navigate(url=self.webpage.url, _timeout=15)
# return if failed to load page
if self.result.failed:
return
# we wait for load event and JavaScript
self._wait_for_load_event_and_js()
except pychrome.exceptions.TimeoutException as e:
self.result.set_failed(FAILED_REASON_TIMEOUT, type(e).__name__)
def _clear_browser(self):
"""Clears cache, cookies, local storage, etc. of the browser."""
self.tab.Network.clearBrowserCache()
self.tab.Network.clearBrowserCookies()
# store all domains that were requested
first_level_domains = set()
for loaded_url in self.loaded_urls:
# invalid urls raise an exception
try:
first_level_domain = get_fld(loaded_url)
first_level_domains.add(first_level_domain)
except Exception:
pass
# clear the data for each domain
for first_level_domain in first_level_domains:
self.tab.Storage.clearDataForOrigin(origin='.' + first_level_domain, storageTypes='all')
def _deny_permissions(self):
self._deny_permission('notifications')
self._deny_permission('geolocation')
self._deny_permission('camera')
self._deny_permission('microphone')
def _deny_permission(self, permission):
self._set_permission(permission, 'denied')
def _set_permission(self, permission, value):
permission_descriptor = {'name': permission}
self.tab.Browser.setPermission(permission=permission_descriptor, setting=value)
def _wait_for_load_event_and_js(self, load_event_timeout=30, js_timeout=5):
self._wait_for_load_event(load_event_timeout)
# wait for JavaScript code to be run, after the page has been loaded
self.tab.wait(js_timeout)
def _wait_for_load_event(self, load_event_timeout):
# we wait for the load event to be fired (see `_event_load_event_fired`)
waited = 0
while not self._is_loaded and waited < load_event_timeout:
self.tab.wait(0.1)
waited += 0.1
if waited >= load_event_timeout:
self.result.set_stopped_waiting('load event')
self.tab.Page.stopLoading()
############################################################################
# EVENTS
############################################################################
def _event_request_will_be_sent(self, request, requestId, **kwargs):
"""Will be called when a request is about to be sent.
Those requests can still be blocked or intercepted and modified.
This example script does not use any blocking or intercepting.
Note: It does not say anything about the request being successful,
there can still be connection issues.
"""
url = request['url']
self.result.add_request(request_url=url)
# the request id of the first request is stored to be able to detect failures
if self.requestId == None:
self.requestId = requestId
if self.frameId == None:
self.frameId = kwargs.get('frameId', False)
def _event_response_received(self, response, requestId, **kwargs):
"""Will be called when a response is received.
This includes the originating request which resulted in the
response being received.
"""
self.loaded_urls.append(response['url'])
url = response['url']
mime_type = response['mimeType']
status = response['status']
headers = response['headers']
self.result.add_response(requested_url=url, status=status, mime_type=mime_type, headers=headers)
if requestId == self.requestId and (str(status).startswith('4') or str(status).startswith('5')):
self.result.set_failed(FAILED_REASON_STATUS_CODE, str(status))
def _event_loading_failed(self, requestId, errorText, **kwargs):
if requestId == self.requestId:
self.result.set_failed(FAILED_REASON_LOADING, errorText)
def _event_frame_started_loading(self, frameId, **kwargs):
if self.recordNewPagesForClick and frameId == self.frameId:
self._is_loaded = False
self.waitForNavigatedEvent = True
def _event_frame_requested_navigation(self, url, frameId, **kwargs):
is_root_frame = (self.frameId == frameId)
if self.recordNewPagesForClick:
self.click_result.add_new_page(url, root_frame=is_root_frame)
def _event_navigated_within_document(self, url, frameId, **kwargs):
is_root_frame = (self.frameId == frameId)
if self.recordRedirects:
self.result.add_redirect(url, root_frame=is_root_frame)
if self.recordNewPagesForClick:
self.click_result.add_new_page(url, root_frame=is_root_frame)
def _event_window_open(self, url, **kwargs):
if self.recordNewPagesForClick:
self.click_result.add_new_page(url, new_window=True)
def _event_load_event_fired(self, timestamp, **kwargs):
"""Will be called when the page sends an load event.
Note that this only means that all resources are loaded, the
page may still process some JavaScript.
"""
self._is_loaded = True
self.recordRedirects = False
def _event_javascript_dialog_opening(self, message, type, **kwargs):
if type == 'alert':
self.tab.Page.handleJavaScriptDialog(accept=True)
else:
self.tab.Page.handleJavaScriptDialog(accept=False)
############################################################################
# RESULT FOR CLICK ON ELEMENT
############################################################################
def do_click(self, click):
if not click:
return
# get cookies
self.click_result.set_cookies('before_click', self._get_all_cookies())
cookie_notices = self.result.cookie_notices.get(click.detection_technique, [])
if len(cookie_notices) > click.cookie_notice_index:
cookie_notice = cookie_notices[click.cookie_notice_index]
clickables = cookie_notice.get('clickables', [])
if len(clickables) > click.clickable_index:
clickable = clickables[click.clickable_index]
self.recordNewPagesForClick = True
self._click_node(clickable.get('node_id'))
self.tab.wait(1)
# if the frame started loading a new page, we wait
if self.waitForNavigatedEvent:
self._wait_for_load_event(30)
is_page_modal = self.is_page_modal({
'x': cookie_notice.get('x'),
'y': cookie_notice.get('y'),
'width': cookie_notice.get('width'),
'height': cookie_notice.get('height'),
})
self.click_result.set_is_page_modal(is_page_modal)
# check whether cookie notice is still visible
if self._does_node_exist(cookie_notice.get('node_id')):
is_cookie_notice_visible = self.is_node_visible(cookie_notice.get('node_id')).get('is_visible')
self.click_result.set_cookie_notice_visible_after_click(is_cookie_notice_visible)
else:
self.click_result.set_cookie_notice_visible_after_click(False)
# get cookies
self.click_result.set_cookies('after_click', self._get_all_cookies())
############################################################################
# COOKIE NOTICES
############################################################################
def detect_cookie_notices(self, take_screenshots=True):
# check whether the consent management platform is used
# -> there should be a cookie notice
is_cmp_defined = self.is_cmp_function_defined()
self.result.set_cmp_defined(is_cmp_defined)
# find cookie notice by using AdblockPlus rules
cookie_notice_filters = {}
for abp_filter_name, abp_filter in self.abp_filters.items():
cookie_notice_rule_node_ids = set(self.find_cookie_notices_by_rules(abp_filter))
cookie_notice_rule_node_ids = self._filter_visible_nodes(cookie_notice_rule_node_ids)
self.result.add_cookie_notices(abp_filter_name, self.get_properties_of_cookie_notices(cookie_notice_rule_node_ids))
cookie_notice_filters[abp_filter_name] = cookie_notice_rule_node_ids
# find string `cookie` in nodes and store the closest parent block element
cookie_node_ids = self.search_for_string('cookie')
cookie_node_ids = self._filter_visible_nodes(cookie_node_ids)
cookie_node_ids = set([self.find_parent_block_element(node_id) for node_id in cookie_node_ids])
cookie_node_ids = [cookie_node_id for cookie_node_id in cookie_node_ids if cookie_node_id is not None]
# find fixed parent nodes (i.e. having style `position: fixed`) with string `cookie`
cookie_notice_fixed_node_ids = self.find_cookie_notices_by_fixed_parent(cookie_node_ids)
cookie_notice_fixed_node_ids = self._filter_visible_nodes(cookie_notice_fixed_node_ids)
self.result.add_cookie_notices('fixed_parent', self.get_properties_of_cookie_notices(cookie_notice_fixed_node_ids))
# find full-width parent nodes with string `cookie`
cookie_notice_full_width_node_ids = self.find_cookie_notices_by_full_width_parent(cookie_node_ids)
cookie_notice_full_width_node_ids = self._filter_visible_nodes(cookie_notice_full_width_node_ids)
self.result.add_cookie_notices('full_width_parent', self.get_properties_of_cookie_notices(cookie_notice_full_width_node_ids))
if take_screenshots:
#self.tab.Page.bringToFront()
self.take_screenshot('original')
for filter_name, cookie_notice_filter_node_ids in cookie_notice_filters.items():
self.take_screenshots_of_visible_nodes(cookie_notice_filter_node_ids, f'filter-{filter_name}')
self.take_screenshots_of_visible_nodes(cookie_notice_fixed_node_ids, 'fixed_parent')
self.take_screenshots_of_visible_nodes(cookie_notice_full_width_node_ids, 'full_width_parent')
def get_properties_of_cookie_notices(self, node_ids):
return [self._get_properties_of_cookie_notice(node_id) for node_id in node_ids]
def _get_properties_of_cookie_notice(self, node_id):
js_function = """
function getCookieNoticeProperties(elem) {
if (!elem) elem = this;
const style = getComputedStyle(elem);
// Source: https://codereview.stackexchange.com/a/141854
function powerset(l) {
return (function ps(list) {
if (list.length === 0) {
return [[]];
}
var head = list.pop();
var tailPS = ps(list);
return tailPS.concat(tailPS.map(function(e) { return [head].concat(e); }));
})(l.slice());
}
function getUniqueClassCombinations(elem) {
let result = [];
let classCombinations = powerset(Array.from(elem.classList));
for (var i = 0; i < classCombinations.length; i++) {
let classCombination = classCombinations[i];
if (classCombination.length == 0) {
continue;
}
if (document.getElementsByClassName(classCombination.join(' ')).length == 1) {
result.push(classCombination.join(' '));
}
}
return result;
}
function getUniqueAttributeCombinations(elem) {
function removeFromArray(array, item) {
const index = array.indexOf(item);
if (index > -1) {
array.splice(index, 1);
}
}
let attributes = Array.from(elem.attributes);
let attributeNames = [];
for (var i = 0; i < attributes.length; i++) {
let attributeName = attributes[i].localName;
if (attributeName == 'id' || attributeName == 'class' || attributeName == 'style') {
continue;
}
attributeNames.push(attributeName);
}
let result = [];
let attributeCombinations = powerset(attributeNames);
for (var i = 0; i < attributeCombinations.length; i++) {
let attributeCombination = attributeCombinations[i];
if (attributeCombination.length == 0) {
continue;
}
let selector = '';
for (var j = 0; j < attributeCombination.length; j++) {
let attributeName = attributeCombination[j];
let attributeValue = elem.getAttribute(attributeName);
selector += '[' + attributeName + '="' + attributeValue.replace(/"/g, '\\\\"') + '"]';
}
console.log(selector);
if (document.querySelectorAll(selector).length == 1) {
result.push(attributeCombination.join(' '));
}
}
return result;
}
let width = elem.offsetWidth;
if (width >= document.documentElement.clientWidth) {
width = 'full';
}
let height = elem.offsetHeight;
if (height >= document.documentElement.clientHeight) {
height = 'full';
}
return {
'html': elem.outerHTML,
'has_id': elem.hasAttribute('id'),
'has_class': elem.hasAttribute('class'),
'unique_class_combinations': getUniqueClassCombinations(elem),
'unique_attribute_combinations': getUniqueAttributeCombinations(elem),
'id': elem.getAttribute('id'),
'class': Array.from(elem.classList),
'text': elem.innerText,
'fontsize': style.fontSize,
'width': width,
'height': height,
'x': elem.getBoundingClientRect().left,
'y': elem.getBoundingClientRect().top,
};
}"""
try:
clickables = self.find_clickables_in_node(node_id)
clickables_properties = self.get_properties_of_clickables(clickables)
remote_object_id = self._get_remote_object_id_by_node_id(node_id)
result = self.tab.Runtime.callFunctionOn(functionDeclaration=js_function, objectId=remote_object_id, silent=True).get('result')
cookie_notice_properties = self._get_object_for_remote_object(result.get('objectId'))
cookie_notice_properties['node_id'] = node_id
cookie_notice_properties['clickables'] = clickables_properties
cookie_notice_properties['is_page_modal'] = self.is_page_modal({
'x': cookie_notice_properties.get('x'),
'y': cookie_notice_properties.get('y'),
'width': cookie_notice_properties.get('width'),
'height': cookie_notice_properties.get('height'),
})
return cookie_notice_properties
except pychrome.exceptions.CallMethodException as e:
self.result.add_warning({
'message': str(e),
'exception': type(e).__name__,
'traceback': traceback.format_exc().splitlines(),
'method': '_get_cookie_notice_properties',
})
cookie_notice_properties = dict.fromkeys([
'html', 'has_id', 'has_class', 'unique_class_combinations',
'unique_attribute_combinations', 'id', 'class', 'text',
'fontsize', 'width', 'height', 'x', 'y', 'node_id', 'clickables',
'is_page_modal'])
cookie_notice_properties['clickables'] = []
return cookie_notice_properties
############################################################################
# GENERAL
############################################################################
def detect_language(self):
try:
result = self.tab.Runtime.evaluate(expression='document.body.innerText').get('result')
language = detect(result.get('value'))
self.result.set_language(language)
except Exception as e:
self.result.add_warning({
'message': str(e),
'exception': type(e).__name__,
'traceback': traceback.format_exc().splitlines(),
'method': 'detect_language',
})
def search_for_string(self, search_string):
"""Searches the DOM for the given string and returns all found nodes."""
# stop execution of scripts to ensure that results do not change during search
self.tab.Emulation.setScriptExecutionDisabled(value=True)
# search for the string in a text node
# take the parent of the text node (the element that contains the text)
# this is necessary if an element contains more than one text node!
# see for explanation:
# - https://stackoverflow.com/a/2994336
# - https://stackoverflow.com/a/11744783
search_object = self.tab.DOM.performSearch(
query="//body//*/text()[contains(translate(., 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), '" + search_string + "')]/parent::*")
node_ids = []
if search_object.get('resultCount') != 0:
search_results = self.tab.DOM.getSearchResults(
searchId=search_object.get('searchId'),
fromIndex=0,
toIndex=int(search_object.get('resultCount')))
node_ids = search_results.get('nodeIds')
# remove script and style nodes
node_ids = [node_id for node_id in node_ids if not self._is_script_or_style_node(node_id)]
# resume execution of scripts
self.tab.Emulation.setScriptExecutionDisabled(value=False)
# return nodes
return node_ids
def find_parent_block_element(self, node_id):
"""Returns the nearest parent block element or the element itself if it is a block element."""
js_function = """
function findClosestBlockElement(elem) {
function isInlineElement(elem) {
const style = getComputedStyle(elem);
return style.display == 'inline';
}
if (!elem) elem = this;
while(elem && elem !== document.body && isInlineElement(elem)) {
elem = elem.parentNode;
}
return elem;
}"""
try:
remote_object_id = self._get_remote_object_id_by_node_id(node_id)
result = self.tab.Runtime.callFunctionOn(functionDeclaration=js_function, objectId=remote_object_id, silent=True).get('result')
return self._get_node_id_for_remote_object(result.get('objectId'))
except pychrome.exceptions.CallMethodException as e:
self.result.add_warning({
'message': str(e),
'exception': type(e).__name__,
'traceback': traceback.format_exc().splitlines(),
'method': 'find_parent_block_element',
})
return None
############################################################################
# COOKIE NOTICE DETECTION: FULL WIDTH PARENT
############################################################################
def find_cookie_notices_by_full_width_parent(self, cookie_node_ids):
cookie_notice_full_width_node_ids = set()
for node_id in cookie_node_ids:
fwp_result = self._find_full_width_parent(node_id)
if fwp_result.get('parent_node_exists'):
cookie_notice_full_width_node_ids.add(fwp_result.get('parent_node'))
return cookie_notice_full_width_node_ids
def _find_full_width_parent(self, node_id):
js_function = """
function findFullWidthParent(elem) {
function parseValue(value) {
var parsedValue = parseInt(value);
if (isNaN(parsedValue)) {
return 0;
} else {
return parsedValue;
}
}
function getWidth(elem) {
const style = getComputedStyle(elem);
return elem.clientWidth +
parseValue(style.borderLeftWidth) + parseValue(style.borderRightWidth) +
parseValue(style.marginLeft) + parseValue(style.marginRight);
}
function getHeight(elem) {
const style = getComputedStyle(elem);
return elem.clientHeight +
parseValue(style.borderTopWidth) + parseValue(style.borderBottomWidth) +
parseValue(style.marginTop) + parseValue(style.marginBottom);
}
function getVerticalSpacing(elem) {
const style = getComputedStyle(elem);
return parseValue(style.paddingTop) + parseValue(style.paddingBottom) +
parseValue(style.borderTopWidth) + parseValue(style.borderBottomWidth) +
parseValue(style.marginTop) + parseValue(style.marginBottom);
}
function getHeightDiff(outerElem, innerElem) {
return getHeight(outerElem) - getHeight(innerElem);
}
function isParentHigherThanItsSpacing(outerElem, innerElem) {
let allowedIncrease = Math.max(0.25*getHeight(innerElem), 20);
return getHeightDiff(outerElem, innerElem) > (getVerticalSpacing(outerElem) + allowedIncrease);
}
function getPosition(elem) {
return elem.getBoundingClientRect().top;
}
function getPositionDiff(outerElem, innerElem) {
return Math.abs(getPosition(outerElem) - getPosition(innerElem));
}
function getPositionSpacing(outerElem, innerElem) {
const outerStyle = getComputedStyle(outerElem);
const innerStyle = getComputedStyle(innerElem);
return parseValue(innerStyle.marginTop) +
parseValue(outerStyle.paddingTop) + parseValue(outerStyle.borderTopWidth)
}
function isParentMovedMoreThanItsSpacing(outerElem, innerElem) {
let allowedIncrease = Math.max(0.25*getHeight(innerElem), 20);
return getPositionDiff(outerElem, innerElem) > (getPositionSpacing(outerElem, innerElem) + allowedIncrease);
}
if (!elem) elem = this;
while(elem && elem !== document.body) {
parent = elem.parentNode;
if (isParentHigherThanItsSpacing(parent, elem) || isParentMovedMoreThanItsSpacing(parent, elem)) {
break;
}
elem = parent;
}
let allowedIncrease = 18; // for scrollbar issues
if (document.documentElement.clientWidth <= (getWidth(elem) + allowedIncrease)) {
return elem;
} else {
return false;
}
}"""
try:
remote_object_id = self._get_remote_object_id_by_node_id(node_id)
result = self.tab.Runtime.callFunctionOn(functionDeclaration=js_function, objectId=remote_object_id, silent=True).get('result')
# if a boolean is returned, we did not find a full-width small parent
if result.get('type') == 'boolean':
return {
'parent_node_exists': result.get('value'),
'parent_node': None,
}
# otherwise, we found one
else:
return {
'parent_node_exists': True,
'parent_node': self._get_node_id_for_remote_object(result.get('objectId')),
}
except pychrome.exceptions.CallMethodException as e:
self.result.add_warning({
'message': str(e),
'exception': type(e).__name__,
'traceback': traceback.format_exc().splitlines(),
'method': '_find_full_width_parent',
})
return {
'parent_node_exists': False,
'parent_node': None,
}
############################################################################
# COOKIE NOTICE DETECTION: FIXED PARENT
############################################################################