Reputation: 23
I have a string which of value changes, and I need to put this string into an input field.
(async () => {
let pageNum = 1004327;
let browser = await puppeteer.launch({
headless: true,
});
let page = await browser.newPage();
while (1) {
await page.goto(`${link}${pageNum}`);
page.setDefaultTimeout(0);
let html = await page.evaluate(async () => {
let mail = document.getElementById(
"ctl00_phWorkZone_DbLabel8"
).innerText;
let obj = {
email: mail,
link: window.location.href,
};
return obj;
});
if (Object.values(html)[0]) {
await staff.type(
"textarea[name=mail_address]",
Object.values(html).join("\n"),
{
delay: 0,
}
);
console.log(pageNum);
pageNum++;
staff.click("input[name=save]", { delay: 0 });
}
}
})();
I used .type()
method, and it works, but I need something faster.
Upvotes: 2
Views: 348
Reputation: 57289
I'm not sure how the input works on the page since it requires auth, but in many cases (depending on how the site listens for changes on the element) you can set the value using browser JS:
staff.$eval(
'textarea[name="mail_address"]',
(el, value) => el.value = value,
evalObject.values(html).join("\n")
);
Runnable, minimal example:
const puppeteer = require("puppeteer"); // ^19.6.3
const html = `<!DOCTYPE html><html><body>
<textarea name="mail_address"></textarea></body></html>`;
let browser;
(async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
await page.setContent(html);
const sel = 'textarea[name="mail_address"]';
await page.$eval(
sel,
(el, value) => el.value = value,
"testing"
);
console.log(await page.$eval(sel, el => el.value)); // => testing
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
If this doesn't work, you can try triggering a change handler on the element with a trusted Puppeteer keyboard action or manually with an untrusted JS browser event. You can also use keyboard.sendCharacter
when focus is on the element, as pointed out in this answer:
await page.focus(selector);
await page.keyboard.sendCharacter("foobar");
Note that in your original code, .setDefaultTimeout(0);
is risky because it can cause the script to hang forever without raising an error. staff.click
and page.authenticate
need await
since they return promises.
Disclosure: I'm the author of the linked blog post.
Upvotes: 0
Reputation: 1967
.type()
method will allow you to fill the input like human typing. Instead of using that, just try .keyboard.sendCharacter()
method (source). It will allow you to fill in the input instantly without typing.
Example how to use it :
const puppeteer=require('puppeteer');
const browser=await puppeteer.launch({ headless: false });
const page=await browser.newPage()
await page.goto("https://stackoverflow.com/q/75395199/12715723")
let input=await page.$('input[name="q"]');
await input.click();
await page.keyboard.sendCharacter('test');
Upvotes: 1