【问题标题】:Failed to Assign Value to InputElement using Puppeteer使用 Puppeteer 为 InputElement 赋值失败
【发布时间】:2022-01-26 02:50:33
【问题描述】:

我正在尝试使用 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")
})();

【问题讨论】:

    标签: javascript css node.js typescript puppeteer


    【解决方案1】:

    我认为您应该从 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");
    

    type 来自Page 类:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 2011-04-19
      • 2012-08-21
      • 2021-04-13
      • 2017-10-11
      • 2021-06-29
      相关资源
      最近更新 更多