Reputation: 623
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 = "[email protected]";
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);
Upvotes: 1
Views: 304
Reputation: 3023
Three ways to get the opened tab:
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.
'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]'),
]);
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);
Upvotes: 2