0

I'm writing a script to scrape data. The page has a list where each item can only be expanded one at a time, where "expanding" means rendering a div under the selected row with some data that is fetched on click. The script looks something like this:

function findData(arr, matches_regex) {
  return Array.prototype.slice
    .call(arr)
    .find((x) => matches_regex(x.textContent))?.textContent;
}

rows = document.getElementsByClassName("selectable-row")
data = []
for (var i = 0; i < rows.length; i++) {
  rows[i].click()
  row_data = document.getElementsByClassName("row-data")
  data1 = findData(row_data, matches_regex_1)
  data2 = findData(row_data, matches_regex_2)

  data.push([data1, data2])
}

The problem is, after rows[i].click() the rest of the script runs before the DOM loads the fetched data, and so data1 and data2 are "undefined" where there should be data. Is there a way to wait for the DOM to fully load after the click before getting the data?

Timr11
  • 1
  • 2
  • What does your `click` event handler look like? You should make that an AJAX call. Also [don't use `getElementsByClassName`](https://stackoverflow.com/questions/54952088/how-to-modify-style-to-html-elements-styled-externally-with-css-using-js/54952474#54952474), especially with loops. – Scott Marcus Jun 30 '22 at 19:39
  • MutationObserver? – SuperStormer Jun 30 '22 at 19:40
  • There is no way possible to wait for whatever you clicked to run. You are going to have to attack this a different way and not knowing what you are doing exactly makes our ability to help you basically impossible. What is loading data? What does that click actually do? – epascarello Jun 30 '22 at 19:46
  • Tried using querySelectorAll, that worked – Timr11 Jul 07 '22 at 22:26

0 Answers0