木偶师 => 如何在标签上循环访问所有<td> <tr> 内容



我需要访问一个具有特定值的td,但这样做,我需要额外确定该特定值所在的行号和td号(表随时间变化,我需要一种通用方法(。我考虑过在两个循环中计算行数和单元格数,所以一旦找到搜索到的值,我就可以提取它的行数和单元数。问题是,一旦我开始对行进行迭代,如何访问每行的所有td?

const rows = await page.$$('.CalendarMonthGrid > :nth-child(1) > div > table > tbody > tr');
for (var i = 0; i < rows.length; i++) {
// how to iterate over the tds?
}

如果您知道您的表列编号每次都完全相同,那么您可以通过只选择td来循环它。在一个循环中创建一个循环是很难维护的,而且基本上它比只创建单个循环慢。例如,您的表包含5列。

let this_row, this_col;
let column = 5; // Specify your column number here
const data = await page.$$('.CalendarMonthGrid > :nth-child(1) > div > table > tbody > tr > td');
for (let i = 0; i < data.length; i++) {
// Here you can find row number for every td by doing this
this_row = Math.ceil( (i + 1)/column )
// Here you can find column number by doing this
this_col = (i + 1) % column
}

如果您的表是动态的,并且具有未知的特定列数和行数,那么您的代码将是这样的。

let this_row, this_col;
const data = await page.$$('.CalendarMonthGrid > :nth-child(1) > div > table > tbody > tr > td');
const row_num = (await page.$$('.CalendarMonthGrid > :nth-child(1) > div > table > tbody > tr > td:nth-child(1)')).length;
const column = data.length / row_num;
for (let i = 0; i < data.length; i++) {
// Here you can find row number for every td by doing this
this_row = Math.ceil( (i + 1)/column )
// Here you can find column number by doing this
this_col = (i + 1) % column
}

取决于您想要做什么,但这是获取元素索引以及元素(在您的情况下是特定的td(的方法之一。

const rows = await page.$$('.CalendarMonthGrid > :nth-child(1) > div > table > tbody > tr');
rows.map((trNode, index) => {
// here you have access to your node + index of it
});

最新更新