【问题标题】:How do I make puppeteer wait for element to load (in a loop)?如何让 puppeteer 等待元素加载(循环)?
【发布时间】:2020-03-28 09:36:36
【问题描述】:

我正在尝试使用 puppeteer 来填写表格并获得结果。 正确提交表单后,会出现一个包含结果的表格,其中包含#some_id。现在我正在寻找一种等到表格加载完成的好方法,如果代码失败,请重做填写表格的过程,直到它正常工作。我希望它做这样的事情(伪代码):

while(table_is_not_loaded){

 get_information;
 fill_in_the_form;
 submit_the_form;

}

我认为使用page.waitForSelector() 函数可能可以实现,但我不能按照我想要的方式使用它,而且如果选择器未准备好或不可见,我也不知道它如何处理错误。

【问题讨论】:

    标签: node.js typescript web-scraping puppeteer google-chrome-headless


    【解决方案1】:

    你可以这样做:

    let table_is_loaded = true;
    await page.waitForSelector('someID').catch(e => table_is_loaded = false);
    
    while(!table_is_loaded){
    
     get_information;
     fill_in_the_form;
     submit_the_form;
    
     table_is_loaded = true;
     await page.waitForSelector('someID').catch(e => table_is_loaded = false);
    }
    

    【讨论】:

    • 我正在使用相同的方法,但是当 puppeteer 到达 waitForSelector() 并且没有找到选择器元素时,它会引发错误并且应用程序崩溃,我不知道如何处理
    • @MirzaPayam 注意到我在那里添加了一个捕获
    【解决方案2】:

    可能是这样的:

    while(true){
      try {
        await page.waitForSelector('#foo')
        get_information;
        fill_in_the_form;
        submit_the_form;
        break
      } catch(e) {
      }
    }
    

    【讨论】:

      【解决方案3】:

      经过一些搜索和尝试不同的代码,我找到了一个解决方案,它使用.$eval() 方法来访问 html 属性并检查元素的高度(您还可以检查其他内容,例如显示或可见性)

      const isNotHidden = await mainPage.$eval(
            "#some_id",
            elem => {
              return (
                window.getComputedStyle(elem).getPropertyValue("height") >= "5px"
              );
            }
          );
      
      

      链接到帮助我实现这一目标的主要答案:https://stackoverflow.com/a/47713155/11968594

      【讨论】:

        猜你喜欢
        • 2019-12-08
        • 2020-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2018-03-15
        • 1970-01-01
        • 2019-12-13
        相关资源
        最近更新 更多