Puppeteer 在错误的选项卡中找到元素

Puppeteer finds the element in the wrong tab

每当我尝试点击产品时,它都会在一个新选项卡中打开,我在其中执行文本内容操作。它 returns 为空,因为人偶操纵者在错误的选项卡中搜索元素

const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({
    "headless": false,
    // "slowMo": 50,
    args: ['--start-fullscreen'],
    defaultViewport: null
});
//Page
const page2 = await browser.newPage();
let username = "g.rajesh690@gmail.com";
let password = "Nation20";
await page2.goto('https://www.flipkart.com');
await page2.waitFor(2000);
await page2.$x("//input[@class='_2zrpKA _1dBPDZ']").then(async ele => {
    await ele[0].type(username);
});
await page2.waitFor(2000);
await page2.$x("//input[@type='password']").then(async ele => {
    await ele[0].type(password);
});
await page2.waitFor(2000);
await page2.$x("//button[@class='_2AkmmA _1LctnI _7UHT_c']").then(async ele => {
    await ele[0].click();
});
await page2.waitFor(3000);
await page2.$x("//input[@class='LM6RPg']").then(async ele => {
    await ele[0].type("iPhone 11");
});
await page2.waitFor(3000);
await page2.$x("//button[@class='vh79eN']").then(async ele => {
    await ele[0].click();
});
await page2.waitFor(2000);
await page2.$x("//div[@class='col col-7-12']/div").then(async ele => {
    await ele[0].click();
});
await page2.waitFor(2000);
let [element] = await page2.$x('//span[@class="_2aK_gu"]');
let text = await page2.evaluate(element => element.textContent, element);
console.log(text);

获取打开标签页的三种方式:

  1. 覆盖 window.open 并将所有(或仅您单击的元素)target="_blank" 属性设置为 "_self",以便在同一选项卡中打开 url:
await page.evaluateOnNewDocument(() => {
    window.open = (new_url) => {window.location.href = new_url}
    for (let i of document.querySelectorAll('[target="_blank"]'))
        i.setAttribute('target', '_self')
    });

注意:这可能不适用于不同来源的框架。

  1. 使用'popup'事件获取弹出页面:
const [popup] = await Promise.all([
  new Promise(resolve => page.once('popup', resolve)),
  //replace the selector with the selector of the button or link you're clicking
  page.click('a[target=_blank]'),
]);
  1. pages()获取新打开的标签:
const pages = await browser.pages();
const popup = pages[pages.length -1];

然后就可以在弹出的页面中找到元素了。例如在您的代码中:

await page.waitFor(2000);
const pages = await browser.pages();
const popup = pages[pages.length -1];

let [element] = await popup.$x('//span[@class="_2aK_gu"]');
let text = await popup.evaluate(element => element.textContent, element);