javascript puppeteer:我如何等待 ajax 请求并处理结果

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51066987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:24:23  来源:igfitidea点击:

puppeteer : how can i wait for ajax request and process the result

javascriptajaxpuppeteer

提问by hretic

so i open a website , waith for all redirects to be done capture captcha image and send it vie nodejs to a user an recive the typed captcha

所以我打开一个网站,等待所有重定向完成捕获验证码图像并将其通过 vie nodejs 发送给用户并接收输入的验证码

    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();

    await page.goto('http://localhost/p1.php' );
    await page.waitForNavigation();

    const captcha_image = await page.$eval('#security', e => e.getAttribute('src'));

    io.emit('send_captcha_to_client' , {text : captcha_image });

    var captcha = await captchaPromise;

after i reciv the typed value of capthca i put it in the field and click the login button

在我收到 capthca 的输入值后,我将其放入该字段并单击登录按钮

    await page.$eval('#W_CAPTCHA', (el , _captcha) => el.value = _captcha.W_CAPTCHA , captcha );

    await page.click('#login-btn');

now after clicking the button a ajax request will be send to the server lets say http://example.com/login.php... and if the captcha is right , i'll get redirected to my dashboard but if the ajax call returns lets say {status:er}

现在点击按钮后,ajax 请求将被发送到服务器让我们说http://example.com/login.php...如果验证码是正确的,我将被重定向到我的仪表板但如果 ajax 调用返回让我们说 {status:er}

and there is <span id="alert"></span>in the page it'll add .Errorclass to it and put the error text in there ... how can i intercept the ajax call and check if the login was successful or not ?

并且 <span id="alert"></span>在页面中它会.Error向它添加类并将错误文本放在那里......我如何拦截ajax调用并检查登录是否成功?

i can cehck the result of ajax call or wait and check the document for div.Errorbut not sure how can i do any of them .. here is my failed attempt !

我可以检查 ajax 调用的结果或等待并检查文档,div.Error但不确定我该怎么做..这是我失败的尝试!

await page.waitForNavigation();

page.waitForSelector('.Error');
const error  = await page.$eval('.Error', e => e.value );

console.log(error);

browser.close();

回答by Aankhen

You can wait on both simultaneously and handle whichever occurs first:

您可以同时等待并处理先发生的情况:

await Promise.race([
  page.waitForNavigation({ waitUntil: "networkidle0" }),
  page.waitForSelector(".Error")
]);

if (await page.$(".Error")) {
  // there was an error
} else {
  // the page changed
}