简体   繁体   English

在 Puppeteer 中无法检测页面上是否存在元素

[英]Unable to detect if an element exists on a page or not in Puppeteer

I'm writing a bot for a pokemon MMORPG game.我正在为口袋妖怪 MMORPG 游戏编写机器人。 I wrote a script to login to my account and move around, the problem is that when I move around, I sometimes find a pokemon and then a new div is created which has the pokemon's data.我写了一个脚本来登录我的帐户并四处走动,问题是当我四处走动时,我有时会找到一个口袋妖怪,然后创建一个包含口袋妖怪数据的新 div。 I also get a button (with the id '#catch') to catch the pokemon.我还有一个按钮(ID 为“#catch”)来捕捉小精灵。 So I wrote the script such that it would check for the #catch button.所以我编写了脚本,以便检查#catch 按钮。 Here's my code这是我的代码

while (true) {
    await page.waitFor(500);
    await page.keyboard.press("ArrowDown");
    if ((await page.$("input#catch")) != null) {
      console.log("Pokemon Found!");
    } else {
      console.log("No Pokemon Found");
    }

however, I get 'No Pokemon Found' every single time, even if there is one.但是,即使有一个,我每次都得到“没有找到口袋妖怪”。

You can check if element exist by using vanilla javascript您可以使用 vanilla javascript 检查元素是否存在

if(document.getElementById('catch').length > 0){
    console.log("Pokemon Found!");
}else{
    console.log("No Pokemon Found");
}

I've found putting 'WaitFor's in code not very reliable or efficient.我发现将“WaitFor”放在代码中不是非常可靠或高效。 If you make them too small, if there is a delay from networking or other reasons, then you have failures.如果你把它们设置得太小,如果网络延迟或其他原因,那么你就会失败。 If you make them huge, then your code take for ever to do.如果你把它们做得很大,那么你的代码就永远不会做。 In my code I've been waitForSelector .在我的代码中,我一直在waitForSelector It has a wait/timeout that can be enlarged.它有一个可以扩大的等待/超时。

Example:例子:

async clickSomeButton(cssSelector) {
    if (await page.waitForSelector(cssSelector, 10000)) {
        await page.click(cssSelector);
        return;
    }
    return fail;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM