最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

getProperties of Puppeteer elementhandle 为空

网站源码admin38浏览0评论

getProperties of Puppeteer elementhandle 为空

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

发布评论

评论列表(0)

  1. 暂无评论