I'm trying to get an XHR response from a webpage. I found the
await page.waitForResponse(url);
or
await page.waitForResponse((res) => {
if (res.url() === myUrl) return true;
});
method, but it always timeout for the url response I'm trying to get.
However, if I set
page.on('response', (res) => {
if (res.url() === myUrl) {
// do what I want with the response
}
})
the correct response is found and I can retrive the data.
After some debugging, seems like waitForResponse() isn't returning any XHR req/res.
Any ideias?
EDIT:
Example. For this case, its required to use puppeteer-extra-plugin-stealth and puppeteer-extra package, otherwise, this URL will return status code '403':
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import UserAgent from 'user-agents';
import puppeteer from 'puppeteer-extra';
import { Page } from 'puppeteer';
const wantedUrl = 'https://www.nike.com.br/DataLayer/dataLayer';
const workingFunction = async (page: Page) => {
let reqCount = 0;
let resCount = 0;
page.on('request', req => {
reqCount++;
if (req.url() == wantedUrl) {
console.log('The request I need: ', req.url());
console.log(reqCount);
}
});
page.on('response', async res => {
resCount++;
if (res.url() == wantedUrl) {
console.log('The response I need:', await res.json());
console.log(resCount);
}
});
await page.goto('https://www.nike.com.br/tenis-nike-sb-dunk-low-pro-unissex-153-169-229-284741', {
timeout: 0,
});
};
const notWorkingFunction = async (page: Page) => {
let resCount = 0;
await page.goto('https://www.nike.com.br/tenis-nike-sb-dunk-low-pro-unissex-153-169-229-284741');
const res = await page.waitForResponse(
res => {
resCount++;
console.log(res.url());
console.log(resCount);
if (res.url() === wantedUrl) {
return true;
}
return false;
},
{ timeout: 0 }
);
return res;
};
(async () => {
puppeteer.use(StealthPlugin());
const browser = await puppeteer.launch({});
const page = await browser.newPage();
const userAgent = new UserAgent({ deviceCategory: 'desktop' });
await page.setUserAgent(userAgent.random().toString());
try {
// workingFunction(page);
const res = await notWorkingFunction(page);
} catch (e) {
console.log(e);
}
})();