找不到元素匹配选择器
Failed to find element matching selector
我正在尝试使用 puppeteer 在输入字段中输入内容,但出现以下错误。
Error: failed to find element matching selector "#cardCvc-input"
我的代码是:
await page.$eval('#cardCvc-input', e => e.value = "000")
DOM中的节点如下:
<input _ngcontent-ng-cli-universal-c1="" autocomplete="off" cccvc="" class="form-control ng-pristine ng-
invalid ng-touched" id="cardCvc-input" maxlength="4" minlength="3" name="cardCvc" pattern="[0-9]{4}|[0-
9]{3}" required="" type="tel">
希望有人能帮助告诉我我做错了什么。请注意,当我检查页面源代码时,我实际上并没有看到 DOM。它是一堆 javascript 代码。这有什么关系吗?
还注意到有iframe父节点。
您可以在调用 evaluate
之前添加一个 waitForSelector
。所以你会等待 DOM 元素被 javascript 代码创建。
await page.waitForSelector('#cardCvc-input');
await page.$eval('#cardCvc-input', e => e.value = "000")
由于元素位于 iframe 中,因此您需要先 select iframe,然后 select 元素:
await page.waitForSelector('iframe'); //make sure you use the correct selector for the iframe
const iframeElement = await page.$('iframe'); //make sure you use the correct selector for the iframe
const frame = await iframeElement.contentFrame();
await frame.waitForSelector('#cardCvc-input');
await frame.$eval('#cardCvc-input', e => e.value = "000");
我正在尝试使用 puppeteer 在输入字段中输入内容,但出现以下错误。
Error: failed to find element matching selector "#cardCvc-input"
我的代码是:
await page.$eval('#cardCvc-input', e => e.value = "000")
DOM中的节点如下:
<input _ngcontent-ng-cli-universal-c1="" autocomplete="off" cccvc="" class="form-control ng-pristine ng-
invalid ng-touched" id="cardCvc-input" maxlength="4" minlength="3" name="cardCvc" pattern="[0-9]{4}|[0-
9]{3}" required="" type="tel">
希望有人能帮助告诉我我做错了什么。请注意,当我检查页面源代码时,我实际上并没有看到 DOM。它是一堆 javascript 代码。这有什么关系吗?
还注意到有iframe父节点。
您可以在调用 evaluate
之前添加一个 waitForSelector
。所以你会等待 DOM 元素被 javascript 代码创建。
await page.waitForSelector('#cardCvc-input');
await page.$eval('#cardCvc-input', e => e.value = "000")
由于元素位于 iframe 中,因此您需要先 select iframe,然后 select 元素:
await page.waitForSelector('iframe'); //make sure you use the correct selector for the iframe
const iframeElement = await page.$('iframe'); //make sure you use the correct selector for the iframe
const frame = await iframeElement.contentFrame();
await frame.waitForSelector('#cardCvc-input');
await frame.$eval('#cardCvc-input', e => e.value = "000");