javascript 如何使用puppeteer在不同的异步函数中打开相同的页面?

kqqjbcuj  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(140)

所以我试图打开相同的url页面,这是写在一个函数是打开在另一个函数.而不是什么我得到的是它打开另一个浏览器窗口.我希望它打开在这相同的浏览器窗口当我打开它使用终端

let openbrowser = async () => {
  const browser = await puppeteer.launch({
    headless: false,
  });
  const page = await browser.newPage();
  page.setViewport({
    width: 1280,
    height: 800,
    isMobile: false,
  });
  await page.goto("https://youtube.com/");
};

let open = async () => {
  const browser = await puppeteer.launch({
    headless: false,
  });

  const page = await browser.newPage();
  page.setViewport({
    width: 1280,
    height: 800,
    isMobile: false,
  });
  await page.goto("https://www.youtube.com/results?search_query=avatar");
};

openbrowser()
open()

我尝试使用此代码,它仍然不从同一窗口打开

let open = async () => {
    openbrowser()
};
jk9hmnmh

jk9hmnmh1#

你打开两个浏览器和两个页面,因此你得到两个页面。
只需重复使用相同的浏览器和页面(即浏览器选项卡)即可导航到下一页:

let openbrowser = async () => {
  // initialize:
  const browser = await puppeteer.launch({ headless: false, });
  const page = await browser.newPage();
  await page.setViewport({ width: 1280, height: 800, isMobile: false, });

  // load first page:
  await page.goto("https://youtube.com/");
  // do stuff with this page, such as: await page.screenshot()

  // navigate to next page:
  await page.goto("https://www.youtube.com/results?search_query=avatar");

  // after all done:
  await page.close();
  await sleep(2000);
  await browser.close();
};

(async() => {
  openbrowser();
})();
    • 更新**

您可以将这段代码拆分为函数,只需传递page对象即可:

const loadPage1 = async (page) => {
  await page.goto("https://youtube.com/");
  // do stuff with this page, such as: await page.screenshot()
};

const loadPage2 = async (page) => {
  await page.goto("https://www.youtube.com/results?search_query=avatar");
  // do other stuff
};

let browser;
(async() => {
  // initialize:
  browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.setViewport({ width: 1280, height: 800, isMobile: false });

  loadPage1(page); // load first page
  loadPage2(page); // navigate to next page

  // after all done:
  await page.close();
  await sleep(2000);
})()
  .catch(err => console.error(err))
  .finally(() => browser?.close());

相关问题