Answer the question
In order to leave comments, you need to log in
How to get element from page in puppeteer?
I have this code:
import puppeteer from 'puppeteer';
import $ from 'jquery';
let page, browser, input;
const contentHtml = `<html><body><input id='test' type='text'></body></html>`;
beforeAll(async () => {
browser = await puppeteer.launch();
page = await browser.newPage();
await page.setContent(contentHtml);
await page.evaluate(() => {
input = page.$('input#test');
console.log(input);
});
});
describe('View', () => {
test('Input is defined', async () => {
expect(input).toBeDefined();
});
});
afterAll(() => {
browser.close();
});
<br>
Evaluation failed: ReferenceError: page is not defined<br>
<br>
at __puppeteer_evaluation_script__:2:5<br>
at ExecutionContext._evaluateInternal (node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:217:19)<br>
at ExecutionContext.evaluate (node_modules/puppeteer/lib/cjs/puppeteer/common/ExecutionContext.js:106:16)<br>
at Object. (src/plugin/tests/view.test.ts:12:3)<br>
Answer the question
In order to leave comments, you need to log in
What happens inside page.evaluate is the equivalent of the browser console on the page.
Accordingly, in this there is not a page object, nor $.
To get this input, you need to use standard JS tools and return a value from promises.
const puppeteer = require('puppeteer');
const contentHtml = `<html><body><input id='test' type='text'></body></html>`;
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent(contentHtml);
const type = await page.evaluate(() => {
return document.getElementById('test').type;
}).catch(e => console.dir(e));
console.dir(type);
await browser.close();
})();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question