我无法识别选择器,我需要迭代一些行并从中获取单元格数据。它看起来像这样:
<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-even
和 ag-row-odd
等等。我读过的所有教程都描述了 td 和 tr 结构,但我在这里没有看到任何类似的元素。
我希望能够按该行号循环遍历每一行,但我不明白如何获取该元素。每行的选择器似乎都是唯一的。此外,我想将单元格作为从这些行生成的类对象的属性。我能够用一个不同的奇怪的表做类似的事情,如下所示:
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));
}
但在这种情况下,选择器之间的唯一区别是末尾的数字,因此很容易循环和更改。有什么想法吗?
最佳答案
您可以使用 .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 中的真实数据测试此示例。与 Try Puppeteer app将上述代码复制到应用程序中并单击“运行它”。
关于javascript - 需要了解表格结构才能抓取网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55931286/