【问题标题】:Puppeteer finds the element in the wrong tabPuppeteer 在错误的选项卡中找到元素
【发布时间】:2020-01-13 07:37:28
【问题描述】:

当我尝试单击产品时,它会在一个新选项卡中打开,我在其中执行文本内容操作。它返回 null,因为 puppeteer 正在错误的选项卡中搜索元素                  

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);

【问题讨论】:

    标签: puppeteer jest-puppeteer


    【解决方案1】:

    三种获取打开标签的方法:

    1. 覆盖window.open 并将所有(或仅您单击的元素)target="_blank" 属性设置为"_self",以便它在同一选项卡中打开网址:
    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);
    

    【讨论】:

      猜你喜欢
      • 2020-01-19
      • 2019-07-21
      • 2020-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-26
      • 1970-01-01
      相关资源
      最近更新 更多