getProperties of Puppeteer elementhandle 为空

编程入门 行业动态 更新时间:2024-10-07 18:30:25

getProperties of Puppeteer elementhandle <a href=https://www.elefans.com/category/jswz/34/1771092.html style=为空"/>

getProperties of Puppeteer elementhandle 为空

我正在尝试编写一些代码来检测任何网站的登录表单(基本上是尝试重新创建类似 1Password 的东西,我可以在其中检测用户名/密码字段)。我想根据元素的属性找出哪些输入是正确的输入。在示例 html 上使用 puppeteer 时,例如:

<form class="">
  <input type="text" id="id1" name="some name" placeholder="some placeholder" value="">
  <input type="text" id="id2" attr1="some name" attr2="some placeholder" value="">
  <input type="text" attr3="some name" attr4="some placeholder" value="">
</form>

Puppeteer 的代码是:

const inputHandles = await page.$$('input')
inputHandles.forEach(async(element) => {
    // This actually works and gives me the id of each of the elements
    const jsHandle = await (await element.getProperty('id')).jsonValue();
    // This always returns {}
    console.log(await element.getProperties())
})

我想知道如何在不专门查询 id/name/placeholder 的情况下动态获取每个输入的属性。我还看到了与 github 上发布的相同问题 ();但是,它因不活动而关闭。谢谢!

回答如下:

您可以使用 getAttributeNames() 获取属性名称。

代码:

const puppeteer = require("puppeteer");

const html = `
    <form class="">
        <input type="text" id="id1" name="some name" placeholder="some placeholder" value="">
        <input type="text" id="id2" attr1="some name" attr2="some placeholder" value="">
        <input type="text" attr3="some name" attr4="some placeholder" value="">
    </form>
`;

let browser;
(async () => {
    browser = await puppeteer.launch();
    const [page] = await browser.pages();
    await page.setContent(html);

    // first variant
    let inputs = await page.$$eval('input', el => el.map(x => x.getAttributeNames().reduce((acc, name) => {return { ...acc, [name]: x.getAttribute(name)};}, {})));
    inputs = inputs.map(x => Object.keys(x).map(k => ({attribute: k, value: x[k]}))).flat();
    console.log(inputs);

    // faster variant
    inputs = await page.$$eval('input', el => el.map(x => Object.fromEntries([...x.attributes].map(attr => [attr.name, attr.value]))));
    inputs = inputs.flatMap(x => Object.entries(x).map(([attribute, value]) => ({attribute, value})));
    console.log(inputs);

})().catch(err => console.error(err)). finally(() => browser ?. close());

附注几天前需要它在这里阅读它blog

更多推荐

getProperties of Puppeteer elementhandle 为空

本文发布于:2024-05-30 14:51:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770612.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:为空   getProperties   Puppeteer   elementhandle

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!