无法使用Puppeter为InputElement分配值



我试图使用puppeteer为html中的Input/TextArea元素设置一个值,但没有成功。代码是用打字稿翻译的。

这里我以YouTube为例。

首先,它应该导航到youtube,然后用伪类css选择器选择输入框,并根据变量设置值:前缀和标题。

脚本一开始执行page.eval就关闭了。我不确定我是否使用了错误的css选择器。当我试图将字符串分配给"时,可能会出现问题;值";属性。

(async ()=>{
const searchbox='html>body>ytd-app>div>div>ytd-masthead>div:nth-of-type(3)/div:nth-of-type(2)/ytd-searchbox/form/div:first-of-type/div:first-of-type/input'
const puppeteer  = require("puppeteer")
const browser = await puppeteer.launch({headless:false, defaultViewport: null, slowMo: 100});
const page = await browser.newPage();
await page.goto('https://www.youtube.com/');
await uploadPhoto("Some", " Video");
async function uploadPhoto(prefix:string, caption:string) {
await page.evaluate( (searchbox:string, prefix:string, caption:string) => {
(document.querySelector(searchbox) as HTMLInputElement).value = `${prefix} ${caption}`},
searchbox, prefix, caption)
}
console.log("finish")
})();

我认为你应该从evaluate函数中删除所有类型,因为这个函数将直接在brwoser中执行,我相信这些类型会使它失败:

async function uploadPhoto(prefix:string, caption:string) {
await page.evaluate( (searchbox, prefix, caption) => {
document.querySelector(searchbox).value = `${prefix} ${caption}`
}, searchbox, prefix, caption)
}

一个更简单的解决方案是使用ElementHandle类中的方法type

const searchInput: ElementHandle<Element> = await page.waitForSelector(searchbox, { timeout: 5000 });
await searchInput.type("Some text to search");

或来自Page类的type

await page.type(searchbox, "Some text to search");

最新更新