【发布时间】:2021-05-22 06:37:41
【问题描述】:
我需要将每个客户端都放在一个表中,这样我就可以遍历它们,并使用 Puppeteer 来抓取一些数据。我需要 MySQL 查询,因为我必须通过查询字符串传递一些参数。
我正在使用 Puppeteer、Puppeteer-cluster(由于有数百行)和 MySQL 驱动程序。
const mysql = require('mysql');
const { Cluster } = require('puppeteer-cluster');
const sql = "select an.id_clientes, ano, c.nome, c.cpf, c.dt_nasc from clientes_anos an inner join clientes c on an.id_clientes = c.id limit 3";
db.query(sql, async (err, result) => {
//console.log(result);
const cluster = await Cluster.launch({
concurrency: Cluster.CONCURRENCY_CONTEXT,
maxConcurrency: 2,
puppeteerOptions: {
headless: false
},
//monitor: true,
timeout: 90000,
});
for (const elem of result){
const cpf = elem.cpf;
const dt = elem.dt_nasc.toLocaleDateString();
const url = `https://servicos.receita.fazenda.gov.br/Servicos/ConsRest/Atual.app/paginas/index.asp?cpf=${cpf}&dtnasc=${dt}`;
console.log(url);
(async()=>{
cluster.on('taskerror', (err, data) => {
//console.log(`Error crawling ${data}: ${err.message}`);
});
await cluster.task(async ({ page, data: url }) => {
console.log(dt, cpf);
await page.goto(url);
await page.type('#data_nascimento', dt);
await page.type('input[name=CPF]', cpf);
await page.waitForNavigation();
try{
const msg = await page.$eval(
`#rfb-main-container table tbody tr:nth-of-type(1) td:nth-of-type(1)`, divs => divs.innerText.trim()
);
if(msg.includes('Resultado encontrado: Saldo inexistente de imposto a pagar ou a restituir.')){
console.log('situação: '+ msg);
}else{
console.log('0');
}
}catch(exception){
console.log('Error');
}
});
await cluster.queue(url);
await cluster.idle();
await cluster.close();
})();
}
});
我遇到的问题是,当页面加载时,await page.type('#data_nascimento', dt); await page.type('input[name=CPF]', cpf); 没有返回正确的值(来自查询的值是正确的),它们正在返回最后一行的值。我打赌它是异步的,但我无法弄清楚。
有什么办法可以解决这个问题吗?
【问题讨论】:
标签: javascript node.js asynchronous async-await puppeteer