最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - Javascript puppeteer code works in debug mode, but not when running using node js - Stack Overflow

programmeradmin1浏览0评论
const puppeteer = require('puppeteer');

(async () => {
  // Launch a new browser instance
  const browser = await puppeteer.launch({ headless: false }); // Set headless to false to see the browser
  const page = await browser.newPage();
  
  // URL of the page to load
  const url = '.p?skuId=6588232';

  // Open the page
  await page.goto(url, { waitUntil: 'domcontentloaded' });

  // Define the selector for the button you are looking for
  const buttonSelector = '.c-button.c-button-primary.c-button-lg.c-button-block.c-button-icon.c-button-icon-leading.add-to-cart-button '; // Replace with your button's selector
  
  // Wait for the button to appear or reload the page
  while (true) {
    try {
      // Try to find the button
      await page.waitForSelector(buttonSelector, { visible: true, timeout: 50000 });
      console.log('Button found!');
      break; // Exit the loop once the button is found
    } catch (error) {
      console.log('Button not found, reloading the page...');
      
      // Reload the page if the button is not found
      await page.reload({ waitUntil: 'domcontentloaded' });
    }
  }
  
  // Close the browser
  await browser.close();
})();

I am trying to reload a webpage until a button is found present on the screen. This code works fine when in debug mode on vscode, but when I try running it using node js it gives me an error.

This is the output when running in node js, the first being my program console output which is expected, but then also a thrown error.

$ node test.js Button not found, reloading the page...
C:\Users\student\Desktop\BestBuyTracker\BestBuyTracker\node_modules\puppeteer-core\lib\cjs\puppeteer\cdp\CDPSession.js:67return Promise.reject(new Errors_js_1.TargetCloseError(Protocol error (${method}): Session closed. Most likely the ${this.#targetType} has been closed.));^ TargetCloseError: Protocol error (Page.reload): Session closed. Most likely the page has been closed.at CdpCDPSession.send (C:\Users\student\Desktop\BestBuyTracker\BestBuyTracker\node_modules\puppeteer-core\lib\cjs\puppeteer\cdp\CDPSession.js:67:35) at CdpPage.reload (C:\Users\student\Desktop\BestBuyTracker\BestBuyTracker\node_modules\puppeteer-core\li b\cjs\puppeteer\cdp\Page.js:667:39) at C:\Users\student\Desktop\BestBuyTracker\BestBuyTracker\test.js:28:18 at process.processTicksAndRejections (node:internal/process/task_queues:105:5)  Node.js v22.13.1
发布评论

评论列表(0)

  1. 暂无评论