需要了解 table 结构才能抓取网页

Need to understand table structure to scrape webpage

我在识别选择器时遇到问题,我需要遍历某些行并从中获取单元格数据。它看起来像这样:

<div class="ag-row ag-row-no-focus ag-row-no-animation ag-row-level-0 ag-row-odd" row="1" style="top: 30px; height: 30px;">
    <div class="ag-cell-no-focus ag-cell ag-cell-not-inline-editing ag-cell-value" tabindex="-1" colid="partnerNo" style="width: 60px; left: 0px; user-select: initial; cursor: text;">
    0010734964
    </div>
    <div class="ag-cell-no-focus ag-cell ag-cell-not-inline-editing ag-cell-value" tabindex="-1" colid="partnerName" style="width: 229px; left: 60px;">
    R.A.G. INDUSTRIAL SOLUTIONS, I NC
    </div>
</div>

行交替为 ag-row-evenag-row-odd 等等。我读过的所有教程都描述了 tdtr 结构,但我在这里没有看到任何类似的元素。

我希望能够按该行号遍历每一行,但我不明白如何获取该元素。每行的选择器似乎都是唯一的。此外,我想将单元格作为从这些行生成的 class 对象的属性。我能够用不同的怪异 table 做类似的事情,就像这样:

for (var i = 0; i < 30; i++) {
    var myIndex = (120 + (i + 1));
    soldToSelector = '#statictext9Mq9nPD4a42Lyx9hdaUFY0_14-listdefintiona5uG8xn1wqkvGe3jrjPaCW_11-cloneINDEX';
    soldToValue = soldToSelector.replace("INDEX", i);
    soldToElement =  await page.$(soldToValue);
    myText =   await page.evaluate(soldToElement => soldToElement.textContent, soldToElement);
    accountsArray.push(new Account((myIndex), myText));
}

但在那种情况下,选择器之间的唯一区别是末尾的数字,因此很容易遍历和更改。有什么想法吗?

似乎该行是由 "row" 属性标识的。您可以尝试这样的操作来获取行数据:

let rows = document.querySelectorAll('[row]');

rows.forEach( (s, i) =>  {

  var cells = s.childNodes;
  cells.forEach( (node , j) => {
    if( node.innerText ) {
      console.log( 'text', j, node.innerText );
      // do something with the text values
    }
  });

});

您可以使用 .ag-row 定位行,使用 .ag-cell 定位每个单元格。然后,您还可以使用 .ag-row > .ag-cell:nth-child(n) 来定位列,其中 n 是列号。

这是一个例子:

const browser = await puppeteer.launch();

const page = await browser.newPage();
await page.goto('https://www.ag-grid.com/example.php#/');

const names = await page.evaluate(() => {
  const firstColumnCells = Array.from(document.querySelectorAll('.ag-row > .ag-cell:nth-child(1)'));
  return firstColumnCells.map(cell => cell.innerText);
});

console.log(names);

await browser.close();

您可以在 demo of Ag-Grid with the Try Puppeteer app 的真实数据上测试此示例,方法是将上述代码复制到应用程序中并单击 "Run It"。