-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecord_catalogs_scraper.py
More file actions
2963 lines (2375 loc) · 96 KB
/
Copy pathrecord_catalogs_scraper.py
File metadata and controls
2963 lines (2375 loc) · 96 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
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
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.actions.wheel_input import ScrollOrigin
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import (
TimeoutException,
StaleElementReferenceException,
NoSuchElementException,
ElementClickInterceptedException,
ElementNotInteractableException,
WebDriverException,
)
import csv
import logging
import math
import os
import time
from datetime import datetime
from auth_utils import switch_to_admin_role as _switch_to_admin_role
logger = logging.getLogger(__name__)
class IncompleteGridScrapeError(WebDriverException):
"""Raised when a grid keeps moving until the configured scroll safety cap."""
ADMIN_ROLE_URL = (
"https://4891605.app.netsuite.com/app/login/secure/changerole.nl?"
"id=4891605~10457~1073~N"
)
RECORD_CATALOG_URL = (
"https://4891605.app.netsuite.com/app/recordscatalog/rcbrowser.nl?whence="
)
TREE_ROOT = '[data-automation-id="RecordSearchResults"]'
TREE_CONTAINER = f'{TREE_ROOT} [data-widget="VirtualTreeContainer"]'
TREE_ITEM = 'li[role="treeitem"][data-widget="TreeItem"]'
FIELDS_GRID = '[data-automation-id="SSAnalyticAPIFieldsDataGrid"]'
JOINS_GRID = '[data-automation-id="SSAnalyticAPIJoinsDataGrid"]'
# Many helper functions below use GRID as the currently active NetSuite grid.
# We switch it between Fields and Joins before scraping each tab.
GRID = FIELDS_GRID
GRID_VIEW = f'{GRID} [data-widget="GridView"]'
GRID_VIEWPORT = f'{GRID} [data-grid-view-section="viewport"]'
GRID_BODY_ROWS = f'{GRID} [data-widget="GridRowSegment"][data-row-type="data"]'
def set_active_grid(grid_css):
"""Switch all generic grid helpers to the selected Record Catalog grid."""
global GRID, GRID_VIEW, GRID_VIEWPORT, GRID_BODY_ROWS
GRID = grid_css
GRID_VIEW = f'{GRID} [data-widget="GridView"]'
GRID_VIEWPORT = f'{GRID} [data-grid-view-section="viewport"]'
GRID_BODY_ROWS = f'{GRID} [data-widget="GridRowSegment"][data-row-type="data"]'
def get_visible_grid_now(driver, grid_css=None):
"""
Returns the visible active Fields/Joins grid, not a hidden stale grid.
NetSuite can keep the previous tab's grid in the DOM after switching
between Fields and Joins. Using document.querySelector() or Selenium's
first matching element can therefore read the wrong hidden grid.
"""
css = grid_css or GRID
try:
return driver.execute_script(
"""
const css = arguments[0];
const grids = [...document.querySelectorAll(css)];
for (const grid of grids) {
const rect = grid.getBoundingClientRect();
const style = window.getComputedStyle(grid);
const visible =
rect.width > 0 &&
rect.height > 0 &&
style.display !== "none" &&
style.visibility !== "hidden" &&
style.opacity !== "0";
if (visible) return grid;
}
return null;
""",
css,
)
except WebDriverException:
return None
TREE_ROW_HEIGHT = 34
# Set this to a small number like 10 while testing.
# Change to None when you are ready to scrape everything.
# TEST_LIMIT = 10
TEST_LIMIT = None
# During long runs, write checkpoint files so a browser/session crash does not
# wipe out all rows already scraped.
CHECKPOINT_EVERY = 50
# V2 outputs are intentionally separate from the earlier files because
# enabling "Show unavailable items" changes the record count and the content.
PARTIAL_FIELDS_FILE = "record_catalogs_fields_v2.partial.csv"
PARTIAL_JOINS_FILE = "record_catalogs_joins_v2.partial.csv"
STATUS_FILE = "record_catalogs_status_v2.csv"
FINAL_FIELDS_FILE = "record_catalogs_fields_v2.csv"
FINAL_JOINS_FILE = "record_catalogs_joins_v2.csv"
# Retry policy:
# - Expand/click failures get up to 2 retries after the first attempt.
# - Records with no catalog tables are treated as verified 0-field/0-join records after verification.
# - Fields + Joins grid scraping gets one retry after the first attempt.
EXPAND_CLICK_MAX_ATTEMPTS = 3
GRID_SCRAPE_MAX_ATTEMPTS = 2
# A virtualized NetSuite grid can ignore one wheel/PageDown event while it is
# hydrating. Never declare the end of a Fields/Joins grid after one stalled
# scroll. The scraper retries the same boundary several times before stopping.
GRID_SCROLL_STALL_MAX_ATTEMPTS = 4
GRID_SCROLL_STALL_RETRY_PAUSE = 0.9
GRID_SCROLL_CHANGE_TIMEOUT = 3
GRID_SCROLL_FALLBACK_TIMEOUT = 2
# Resume repair policy:
#
# The old status file can say ``success`` even when a virtualized grid stopped
# moving early. A status count alone cannot prove that every field was reached.
# Therefore completed records that contain catalog data are queued for a
# ONE-TIME full Fields + Joins repair pass. The repaired status names below are
# final, so later resumes do not keep scraping the same records forever.
#
# Records already proven to have no Fields and no Joins remain untouched.
REPAIR_COMPLETED_CATALOG_RECORDS_ON_RESUME = True
REPAIR_SOURCE_STATUSES = {"success", "verified_zero_joins"}
REPAIR_FINAL_STATUSES = {
"repair_success",
"repair_verified_zero_joins",
"repair_success_zero_fields",
}
# Optional test/scope controls. Use 1-based Record Index values, for example
# {999, 1000}. Leave as None to repair every eligible record from the status.
REPAIR_ONLY_RECORD_INDEXES = None
REPAIR_RECORD_LIMIT = None
# Resume policy:
# - Keep the V2 partial CSVs and V2 status CSV in the same folder.
# - On the next run, the scraper loads them, skips records already marked done,
# and continues with failed/unseen records.
# - IMPORTANT: old no_fields_grid rows are NOT treated as done anymore because
# they can be false positives caused by slow NetSuite loading/connectivity.
RESUME_FROM_CHECKPOINT = True
# Old `no_fields_grid` rows are not final; V2 uses a fresh status file.
# Only `verified_no_catalog_tables` is considered final/no-fields/no-joins.
DONE_STATUSES = {
"success",
"verified_zero_joins",
"verified_no_catalog_tables",
"skipped_missing_name",
*REPAIR_FINAL_STATUSES,
}
# Resume/recheck policy for records that previously succeeded with 0 joins:
# A previous run may have marked Join Count = 0 because the Joins tab was slow
# or connectivity delayed hydration. On resume, these records are deliberately
# re-opened and Joins-only is scraped again. If Joins still returns 0 after the
# full Joins verification sequence, the record is marked verified_zero_joins so
# future resumes can safely skip it.
RECHECK_ZERO_JOINS_ON_RESUME = True
ZERO_JOINS_RECHECK_SOURCE_STATUSES = {"success"}
# Prevent the resume pass from spending minutes rechecking records that had
# neither Fields nor Joins in the previous run. Those are usually empty catalog
# records, not false-zero Joins.
RECHECK_ZERO_JOINS_REQUIRE_EXISTING_FIELDS = True
# If you want to recheck only the first N zero-join records during testing,
# set this to a number like 10. Leave as None for full resume behavior.
ZERO_JOINS_RECHECK_LIMIT = None
# If a record seems to have no fields, verify that conclusion with longer waits
# before writing `verified_no_catalog_tables`.
NO_FIELDS_GRID_VERIFY_ATTEMPTS = 3
NO_FIELDS_GRID_VERIFY_TIMEOUTS = [12, 25, 45]
NO_FIELDS_GRID_RECHECK_PAUSE = 2.5
# Apply the same verification idea to the Joins tab.
# Some records load Fields quickly but hydrate Joins much later. Previously,
# scrape_joins_grid() returned [] after one timeout, which could create a false
# "0 joins" result. These settings make Joins re-check 3 times before accepting
# that a record has no joins.
NO_JOINS_GRID_VERIFY_ATTEMPTS = 3
NO_JOINS_GRID_VERIFY_TIMEOUTS = [12, 25, 45]
NO_JOINS_GRID_RECHECK_PAUSE = 2.5
FIELDNAMES = [
"Record Name",
"Record ID",
"Field ID",
"Name",
"Type",
"Available",
"Feature",
"Permission",
"Join",
"Is Subfield",
"Parent Field ID",
"Field Path",
"Nested Record ID",
"Nested Record Name",
]
JOIN_FIELDNAMES = [
"Record Name",
"Record ID",
"Category Name",
"Category ID",
"Join Type",
"Join Kind",
"Target Name",
"Target Record ID",
"Source Field ID",
"Cardinality",
"Available",
"Condition",
"Is Subjoin",
"Parent Source Field ID",
"Join Path",
]
STATUS_FIELDNAMES = [
"Record Index",
"Record Name",
"Record ID",
"Status",
"Field Count",
"Join Count",
"Attempts",
"Error",
"Timestamp",
]
def switch_to_admin_role(driver):
_switch_to_admin_role(driver, ADMIN_ROLE_URL)
def navigate_to_record_catalog(driver):
logger.info("➡️ Navigating to Record Catalog…")
driver.get(RECORD_CATALOG_URL)
WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.CSS_SELECTOR, TREE_ROOT))
)
WebDriverWait(driver, 20).until(
EC.presence_of_element_located((By.CSS_SELECTOR, TREE_CONTAINER))
)
logger.info("✅ On Record Catalog page.")
def ensure_show_unavailable_items(driver, timeout=15):
"""
Ticks the "Show unavailable items" checkbox before counting/scraping records.
This must happen before get_total_records(), because NetSuite's left tree
can expose additional record types only after this checkbox is enabled.
"""
logger.info("☑️ Ensuring 'Show unavailable items' is checked…")
def find_checkbox(drv):
return drv.execute_script(
"""
const labels = [...document.querySelectorAll("label")];
const label = labels.find(l =>
(l.textContent || "").trim().toLowerCase() === "show unavailable items"
);
if (!label) return null;
const forId = label.getAttribute("for");
if (forId) {
const direct = document.getElementById(forId);
if (direct) return direct;
}
if (label.id) {
const labelled = document.querySelector(`[role="checkbox"][aria-labelledby="${label.id}"]`);
if (labelled) return labelled;
}
const wrapper = label.closest('[data-widget="CheckBox"]');
return wrapper ? wrapper.querySelector('[role="checkbox"]') : null;
"""
)
checkbox = WebDriverWait(driver, timeout).until(find_checkbox)
if (checkbox.get_attribute("aria-checked") or "").lower() != "true":
safe_click(driver, checkbox)
WebDriverWait(driver, timeout).until(
lambda d: (
find_checkbox(d).get_attribute("aria-checked") or ""
).lower() == "true"
)
# Let the virtual tree rebuild after the filter changes.
time.sleep(1.5)
else:
logger.info("☑️ 'Show unavailable items' was already checked.")
WebDriverWait(driver, timeout).until(
EC.presence_of_element_located((By.CSS_SELECTOR, TREE_CONTAINER))
)
def find_right_catalog_tab(driver, tab_name):
"""
Finds a tab from the right-side Record Catalog detail panel only.
The page has two different tab groups:
- left panel: Records / Fields
- right detail panel: Overview / Fields / Joins
This helper intentionally ignores the left panel so selecting "Fields"
never hides the Records tree.
"""
tab_name_lower = tab_name.strip().lower()
return driver.execute_script(
"""
const wanted = arguments[0];
function tabLabel(tab) {
const titleNode = tab.querySelector('[title]');
const title = titleNode ? (titleNode.getAttribute('title') || '').trim() : '';
const text = (tab.textContent || '').trim();
return (title || text).toLowerCase();
}
const tablists = [...document.querySelectorAll('[role="tablist"]')];
for (const list of tablists) {
const tabs = [...list.querySelectorAll('[role="tab"]')];
const labels = tabs.map(tabLabel).filter(Boolean);
const isRightDetailTabs =
labels.includes('overview') &&
labels.includes('fields') &&
labels.includes('joins');
if (!isRightDetailTabs) continue;
for (const tab of tabs) {
if (tabLabel(tab) === wanted) {
return tab;
}
}
}
return null;
""",
tab_name_lower,
)
def ensure_left_records_tab(driver, timeout=10):
"""
Keeps the left panel on the Records tab.
This is a safety net in case a previous run or manual interaction left the
side panel on its own Fields tab, which hides the RecordSearchResults tree.
"""
def find_records_tab(drv):
return drv.execute_script(
"""
function tabLabel(tab) {
const titleNode = tab.querySelector('[title]');
const title = titleNode ? (titleNode.getAttribute('title') || '').trim() : '';
const text = (tab.textContent || '').trim();
return (title || text).toLowerCase();
}
const tablists = [...document.querySelectorAll('[role="tablist"]')];
for (const list of tablists) {
const tabs = [...list.querySelectorAll('[role="tab"]')];
const labels = tabs.map(tabLabel).filter(Boolean);
const isLeftRecordsTabs =
labels.includes('records') &&
labels.includes('fields') &&
!labels.includes('overview') &&
!labels.includes('joins');
if (!isLeftRecordsTabs) continue;
for (const tab of tabs) {
if (tabLabel(tab) === 'records') {
return tab;
}
}
}
return null;
"""
)
try:
tab = WebDriverWait(driver, timeout).until(find_records_tab)
if (tab.get_attribute("aria-selected") or "").lower() != "true":
safe_click(driver, tab)
WebDriverWait(driver, timeout).until(
lambda d: (
find_records_tab(d).get_attribute("aria-selected") or ""
).lower() == "true"
)
time.sleep(0.35)
except TimeoutException:
# Some NetSuite layouts may not expose this tab group immediately.
# Do not fail here; scroll_tree_to_index will still fail loudly if the
# record tree is genuinely unavailable.
pass
def select_catalog_tab(driver, tab_name, timeout=15):
"""
Selects one of the right-side detail tabs: Overview, Fields, or Joins.
This deliberately scopes tab selection to the tablist containing all three
right-side detail tabs. It must not click the left-side Records/Fields tabs.
"""
tab_name_lower = tab_name.strip().lower()
def find_tab(drv):
return find_right_catalog_tab(drv, tab_name_lower) or False
tab = WebDriverWait(driver, timeout).until(find_tab)
if (tab.get_attribute("aria-selected") or "").lower() != "true":
safe_click(driver, tab)
WebDriverWait(driver, timeout).until(
lambda d: (
find_right_catalog_tab(d, tab_name_lower).get_attribute("aria-selected") or ""
).lower() == "true"
)
# Ensure our right-side tab click did not disturb the left-side tree.
ensure_left_records_tab(driver, timeout=5)
time.sleep(0.35)
return tab
def safe_click(driver, element):
"""
More defensive click helper.
NetSuite sometimes exposes SVG nodes or wrapped UI elements where JS
element.click() is not available. Dispatching a real MouseEvent is safer
than blindly calling arguments[0].click().
"""
try:
element.click()
return
except (
ElementClickInterceptedException,
ElementNotInteractableException,
StaleElementReferenceException,
WebDriverException,
):
pass
try:
driver.execute_script(
"""
const el = arguments[0];
if (!el) {
throw new Error("safe_click received a null element");
}
if (typeof el.click === "function") {
el.click();
return;
}
el.dispatchEvent(new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window
}));
""",
element,
)
return
except WebDriverException:
# Final fallback: use Selenium mouse movement/click.
ActionChains(driver).move_to_element(element).click().perform()
def set_scroll_top(driver, element, top):
"""
NetSuite's tree is virtualized, so we scroll the virtual container directly
and fire a scroll event to force it to render the next batch of records.
"""
driver.execute_script(
"""
const el = arguments[0];
const top = arguments[1];
el.scrollTop = top;
el.dispatchEvent(new Event('scroll', { bubbles: true }));
""",
element,
top,
)
time.sleep(0.35)
def get_tree_container(driver):
return WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.CSS_SELECTOR, TREE_CONTAINER))
)
def get_total_records(driver):
"""
Reads aria-setsize from any visible top-level record.
Your pasted HTML shows aria-setsize="2040".
"""
item = WebDriverWait(driver, 10).until(
EC.presence_of_element_located(
(By.CSS_SELECTOR, f'{TREE_ITEM}[aria-level="0"][aria-setsize]')
)
)
raw_total = item.get_attribute("aria-setsize")
try:
return int(raw_total)
except (TypeError, ValueError):
logger.warning("⚠️ Could not read total record count; falling back to 2000.")
return 2000
def scroll_tree_to_index(driver, index):
container = get_tree_container(driver)
set_scroll_top(driver, container, index * TREE_ROW_HEIGHT)
selector = f'{TREE_ITEM}[aria-level="0"][data-index="{index}"]'
return WebDriverWait(driver, 10).until(
lambda d: next(
(
item
for item in d.find_elements(By.CSS_SELECTOR, selector)
if item.is_displayed()
),
False,
)
)
def extract_record_identity(record_item):
"""
Top-level record rows usually have:
- first text span: display name
- second text span: script/internal id
For [Missing Label:...] records, the second span may be blank in some cases,
so we derive the internal id from the missing-label path.
"""
spans = record_item.find_elements(
By.CSS_SELECTOR,
'[data-tree-section="content"] span[data-widget="Text"]',
)
texts = [span.text.strip() for span in spans if span.text.strip()]
record_name = texts[0] if texts else ""
record_id = texts[1] if len(texts) > 1 else ""
if not record_id and record_name.startswith("[Missing Label:"):
cleaned = record_name.strip("[]")
record_id = cleaned.split(".")[-1]
return record_name, record_id
def expand_record(driver, record_item):
"""
Expands one top-level record so the child 'SuiteScript and REST Query API'
appears underneath.
"""
parent_id = record_item.get_attribute("id")
if record_item.get_attribute("aria-expanded") != "true":
expander = record_item.find_element(
By.CSS_SELECTOR,
'[data-tree-section="expander"]',
)
safe_click(driver, expander)
child_selector = (
f'{TREE_ITEM}[aria-level="1"][data-parent-item-id="{parent_id}"]'
)
child = WebDriverWait(driver, 10).until(
lambda d: next(
(
item
for item in d.find_elements(By.CSS_SELECTOR, child_selector)
if "SuiteScript and REST Query API" in item.text
),
False,
)
)
return parent_id, child
def collapse_record(driver, parent_id):
"""
Collapse after each scrape so data-index scrolling remains predictable.
"""
try:
parent = driver.find_element(By.ID, parent_id)
if parent.get_attribute("aria-expanded") == "true":
expander = parent.find_element(
By.CSS_SELECTOR,
'[data-tree-section="expander"]',
)
safe_click(driver, expander)
time.sleep(0.15)
except Exception:
pass
def get_grid(driver, grid_css=None, timeout=15):
css = grid_css or GRID
return WebDriverWait(driver, timeout).until(
lambda d: get_visible_grid_now(d, css) or False
)
def grid_signature(driver):
"""
Returns a lightweight signature of the visible active grid so we can tell
whether NetSuite has actually replaced/refreshed it.
"""
try:
grid = get_visible_grid_now(driver, GRID)
if not grid:
return ""
rows = grid.find_elements(
By.CSS_SELECTOR,
'[data-widget="GridRowSegment"]',
)
parts = []
for row in rows[:20]:
parts.append(
"|".join([
row.get_attribute("data-row-id") or "",
row.get_attribute("data-row-type") or "",
row.get_attribute("data-index") or "",
row.text.strip()[:80],
])
)
return "||".join(parts)
except Exception:
return ""
def record_tokens(record_name, record_id):
tokens = []
for value in [record_id, record_name]:
value = (value or "").strip()
if value:
tokens.append(value)
if value.startswith("[Missing Label:"):
tokens.append(value.strip("[]").split(".")[-1])
return [t for t in dict.fromkeys(tokens) if t]
def wait_for_grid_to_match_record(driver, record_name, record_id, old_signature="", timeout=25):
"""
Wait until the visible right-side Fields grid belongs to the selected record,
not the previous record or the hidden Joins tab.
"""
tokens = record_tokens(record_name, record_id)
def ready(drv):
try:
grid = get_visible_grid_now(drv, GRID)
if not grid:
return False
text = grid.text.strip()
sig = grid_signature(drv)
if old_signature and sig == old_signature:
return False
if not text:
return False
# Best case: synthetic header contains the record id/name.
if any(token in text for token in tokens):
return grid
# Fallback: if the visible grid signature changed and rows exist,
# allow it, but only after a real DOM change.
data_rows = grid.find_elements(
By.CSS_SELECTOR,
'[data-widget="GridRowSegment"][data-row-type="data"]',
)
if sig and sig != old_signature and data_rows:
return grid
return False
except (NoSuchElementException, StaleElementReferenceException, WebDriverException):
return False
return WebDriverWait(driver, timeout).until(ready)
def get_grid_scroll_box(driver, axis="y"):
"""
Finds the actual scrollable element inside the visible active NetSuite grid.
Do not assume [data-grid-view-section="viewport"] is always the scroll box.
"""
grid = get_grid(driver)
script = """
const grid = arguments[0];
const axis = arguments[1];
if (!grid) return null;
const nodes = [grid, ...grid.querySelectorAll("*")];
let best = null;
let bestRange = 0;
for (const el of nodes) {
const rect = el.getBoundingClientRect();
if (rect.width < 20 || rect.height < 20) continue;
const range = axis === "y"
? el.scrollHeight - el.clientHeight
: el.scrollWidth - el.clientWidth;
if (range > bestRange) {
best = el;
bestRange = range;
}
}
return best || grid.querySelector('[data-widget="GridView"]') || grid;
"""
box = driver.execute_script(script, grid, axis)
return box or grid
def visible_grid_row_indexes(driver):
try:
grid = get_visible_grid_now(driver, GRID)
if not grid:
return []
rows = grid.find_elements(
By.CSS_SELECTOR,
'[data-widget="GridRowSegment"][data-row-type="data"]',
)
indexes = []
for row in rows:
raw = row.get_attribute("data-index")
if raw is not None:
try:
indexes.append(int(raw))
except ValueError:
pass
return sorted(set(indexes))
except Exception:
return []
def reset_grid_scroll(driver, timeout=10):
"""
Reset both horizontal and vertical scrolls.
Then wait until the first visible data row is row 1, or until we confirm
there is no vertical scrolling needed.
"""
y_box = get_grid_scroll_box(driver, "y")
x_box = get_grid_scroll_box(driver, "x")
driver.execute_script(
"""
const y = arguments[0];
const x = arguments[1];
if (y) {
y.scrollTop = 0;
y.dispatchEvent(new Event("scroll", { bubbles: true }));
y.dispatchEvent(new WheelEvent("wheel", {
deltaY: -1000,
bubbles: true,
cancelable: true
}));
}
if (x) {
x.scrollLeft = 0;
x.dispatchEvent(new Event("scroll", { bubbles: true }));
}
""",
y_box,
x_box,
)
def top_ready(drv):
try:
info = drv.execute_script(
"""
const el = arguments[0];
return {
top: el ? el.scrollTop : 0,
range: el ? (el.scrollHeight - el.clientHeight) : 0
};
""",
y_box,
)
indexes = visible_grid_row_indexes(drv)
if info["range"] <= 5:
return True
return info["top"] <= 2 and (not indexes or min(indexes) <= 1)
except StaleElementReferenceException:
return False
try:
WebDriverWait(driver, timeout).until(top_ready)
except TimeoutException:
# Do not crash. We will still scrape whatever becomes visible.
pass
time.sleep(0.4)
def scroll_grid_down(driver):
"""
Scrolls the actual grid scroll container, not just the page.
Also fires wheel/scroll events because NetSuite UI components often listen
to synthetic scroll events.
"""
y_box = get_grid_scroll_box(driver, "y")
return driver.execute_script(
"""
const el = arguments[0];
const before = el.scrollTop;
const maxTop = Math.max(0, el.scrollHeight - el.clientHeight);
const step = Math.max(180, Math.floor(el.clientHeight * 0.75));
el.scrollTop = Math.min(maxTop, before + step);
el.dispatchEvent(new Event("scroll", { bubbles: true }));
el.dispatchEvent(new WheelEvent("wheel", {
deltaY: step,
bubbles: true,
cancelable: true
}));
return {
before,
after: el.scrollTop,
maxTop,
clientHeight: el.clientHeight,
scrollHeight: el.scrollHeight,
atBottom: el.scrollTop >= maxTop - 3
};
""",
y_box,
)
def get_grid_viewport(driver):
"""
The visible viewport inside the active NetSuite Record Catalog grid.
Native wheel scrolling should target this element.
"""
grid = get_grid(driver)
return WebDriverWait(driver, 15).until(
lambda d: next(
(
vp for vp in grid.find_elements(
By.CSS_SELECTOR,
'[data-grid-view-section="viewport"]'
)
if vp.is_displayed()
),
False,
)
)
def focus_fields_grid(driver):
"""
Focus the grid before keyboard/wheel scrolling.
"""
grid = get_grid(driver)
driver.execute_script(
"arguments[0].scrollIntoView({block: 'center', inline: 'center'});",
grid,
)
try:
ActionChains(driver).move_to_element(grid).click().perform()
except Exception:
driver.execute_script("arguments[0].focus();", grid)
time.sleep(0.2)
return grid
def native_wheel_grid(driver, delta_y, pause=0.45):
"""
Sends a real browser wheel event over the NetSuite grid viewport.
This is closer to what happens when you manually scroll the table.
"""
viewport = get_grid_viewport(driver)
try:
origin = ScrollOrigin.from_element(viewport)
ActionChains(driver).scroll_from_origin(origin, 0, delta_y).perform()
except Exception:
# Fallback for Selenium/browser combinations where wheel input fails.
driver.execute_script(
"""
const el = arguments[0];
const dy = arguments[1];
el.dispatchEvent(new WheelEvent("wheel", {
deltaY: dy,
deltaMode: 0,
bubbles: true,
cancelable: true
}));
const candidates = [el, ...el.querySelectorAll("*")];
const scrollable = candidates.find(x => x.scrollHeight > x.clientHeight + 5);
if (scrollable) {
scrollable.scrollTop += dy;
scrollable.dispatchEvent(new Event("scroll", { bubbles: true }));
}
""",
viewport,
delta_y,
)
time.sleep(pause)
def wait_for_visible_indexes_change(driver, old_indexes, timeout=6):
"""
Wait until NetSuite renders a different row range after scrolling.
"""
old_tuple = tuple(old_indexes)
try:
WebDriverWait(driver, timeout).until(
lambda drv: tuple(visible_grid_row_indexes(drv)) != old_tuple
)