Javascript 梦魇EJS-如何读取表格行内容?
我正在编写一个小的噩梦脚本,它在web表单中键入名称并读取打印在表中的结果。我已经进行了输入输入,得到如下表格结果:Javascript 梦魇EJS-如何读取表格行内容?,javascript,web-scraping,bots,nightmare,Javascript,Web Scraping,Bots,Nightmare,我正在编写一个小的噩梦脚本,它在web表单中键入名称并读取打印在表中的结果。我已经进行了输入输入,得到如下表格结果: { jQuery110205953448106032428: 124 } // ... .wait(2000) .evaluate(function () { // get table and prepare result const table = document.querySelector('table#t_comun'),
{ jQuery110205953448106032428: 124 }
// ...
.wait(2000)
.evaluate(function () {
// get table and prepare result
const table = document.querySelector('table#t_comun'),
result = [];
// get rows
const rows = table.querySelectorAll( 'tr' );
for( let i=0; i<rows.length; i++ ) {
// get cells
let cells = rows[i].querySelectorAll( 'td' );
// get contents
let row = [];
for( j=0; j<cells.length; j++ ) {
row.push( cells[i].innerHTML );
}
// add to result
result.push( row );
}
// done, return result
return result;
})
.end()
// ...
所以我不知道如何从这个元素中读取行
我当前的脚本是:
const Nightmare = require('nightmare')
const nightmare = Nightmare({ show: true })
nightmare
.goto('https://rnped.segob.gob.mx/')
.click('small#leyendacomun')
.wait(2000)
.type('input#comun_c_nombre', 'María')
.type('input#comun_c_apaterno', 'Hernández')
.click('button#busca_comun')
.wait(2000)
.evaluate(function () {
return document.querySelector('table#t_comun')
// Here I select and return the <table>
})
.end()
.then(function (result) {
console.log(result)
// Here I get { jQuery110205953448106032428: 124 }
})
.catch(function (error) {
console.error('Error:', error);
});
如何从该查询选择器获取表行?evaluate的结果不能像代码中那样引用DOM元素。执行评估函数中的所有数据提取,例如:
{ jQuery110205953448106032428: 124 }
// ...
.wait(2000)
.evaluate(function () {
// get table and prepare result
const table = document.querySelector('table#t_comun'),
result = [];
// get rows
const rows = table.querySelectorAll( 'tr' );
for( let i=0; i<rows.length; i++ ) {
// get cells
let cells = rows[i].querySelectorAll( 'td' );
// get contents
let row = [];
for( j=0; j<cells.length; j++ ) {
row.push( cells[i].innerHTML );
}
// add to result
result.push( row );
}
// done, return result
return result;
})
.end()
// ...
好的,非常感谢!我如何迭代结果表的所有页面,我也必须在evaluate函数中进行迭代?您可以在自己的浏览器中进行测试:编写一个脚本,将您需要的所有数据提取到数组或对象中。然后在求值函数中使用相同的代码并返回结果。@RameshKumar在调用querySelectorAll时出现了什么样的错误?您是否已验证至少表中前面的元素不为空?