简体   繁体   English

如何使用 Puppeteer 按名称获取元素值?

[英]How would I get an element value by name using Puppeteer?

I want to get the value of this我想得到这个的价值

<input type="hidden" value="12345" name="InitiationTT">

But since it does not have an ID, I would like to retrieve the value by name.但由于它没有 ID,我想按名称检索值。 I first tried this:我首先尝试了这个:

const cii = await page.$("InitiationTT");
const init = await page.evaluate(el => el.getAttribute("value"), cii);

which did not work and threw TypeError: Cannot read properties of null (reading 'getAttribute') , so then I tried this:这不起作用并抛出TypeError: Cannot read properties of null (reading 'getAttribute') ,所以我尝试了这个:

const cii = page.evaluate(() => {document.querySelector("input[name=InitiationTT]").value});

which gave me Promise { <pending> } and so I finally tried this:这给了我Promise { <pending> } ,所以我终于尝试了这个:

const cii = document.querySelector("input[name=InitiationTT]").value;

Which gave me ReferenceError: document is not defined so I am assuming that is because I am using NodeJS(?)这给了我ReferenceError: document is not defined所以我假设这是因为我使用的是 NodeJS(?)

These 3 methods did not work and I do not know if Puppeteer has a way of getting a value of an element by it's name.这 3 种方法不起作用,我不知道 Puppeteer 是否可以通过名称获取元素的值。 Any help would be appreciated.任何帮助,将不胜感激。

Make sure your selector is correct.确保您的选择器是正确的。 Furthermore, the value property should be available on the <input> element.此外, value属性应该在<input>元素上可用。

const r = await page.$eval('input[name="InitiationTT"]', ({ value }) => value); // 12345

Reference: How to get element value in puppeteer参考: 如何在 puppeteer 中获取元素值


Note: A similar question has been asked before:注意:之前有人问过类似的问题:

Get the Value of HTML Attributes Using Puppeteer 使用 Puppeteer 获取 HTML 属性的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM