Puppeteer finds the element in the wrong tab

家住魔仙堡 提交于 2020-01-24 20:41:05

问题


When ever I tried to click on the product, it opens in a new tab, where I perform text content operation. It returns null as puppeteer is searching the element in wrong tab                  

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:


Three ways to get the opened tab:

  1. override window.open and set all (or only the element you click on) target="_blank" attributes to "_self" so it opens the url in the same tab:
await page.evaluateOnNewDocument(() => {
    window.open = (new_url) => {window.location.href = new_url}
    for (let i of document.querySelectorAll('[target="_blank"]'))
        i.setAttribute('target', '_self')
    });

Note: that may not work in frames with different origins.

  1. get the popup page using 'popup' event:
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. get the newly opened tab from pages():
const pages = await browser.pages();
const popup = pages[pages.length -1];

Then you can find the element in the popup page. For instance in your code:

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


来源:https://stackoverflow.com/questions/59712283/puppeteer-finds-the-element-in-the-wrong-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!