javascript - 无法使用 node.js/puppeteer 上传图像文件

标签 javascript node.js puppeteer

到目前为止,我已经尝试了两件事。

const iconupload = await page.$x(xpath); //Triple-checked that this x path is correct
iconupload[0].uploadFile(picture); //Triple-checked that this picture path is correct

await page.evaluate((picturepath) => {
    document.querySelector('input[type=file]').value = picturepath
}, picturepath);

对于第一种方法,我得到一个

TypeError: Cannot read property 'uploadFile' of undefined

对于第二种方法,我得到一个

Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

有没有办法将图像上传到此输入?

最佳答案

已解决

事实证明,有问题的图像输入位于 iframe 元素内。在做了一些挖掘之后,我发现如果页面内部包含一个 iframe 元素,那么正常的 puppeteer 函数将不起作用。这是因为,根据 documentation ,page.$x、page.$ 和 page.waitFor 等典型的 puppeteer 函数实际上是 page.mainFrame().$x、page.mainFrame().$ 和 page.mainFrame().waitFor() 的快捷方式。因此,这些方法不适用于页面中包含的辅助框架

以下是我为克服这个问题所做的工作。我首先从 src 属性得到了 iframe 的链接。然后,我创建了一个新页面,并将这个新页面转到此链接。然后,我可以像往常一样抓取。这是我的代码的释义片段:

let framelink = await page.evaluate(() => {
     return document.getElementsByTagName('iframe')[1].src;
}); 
const picturepage = await browser.newPage();
picturepage.goto(framelink)

//Now I can just scrape normally using methods like picturepage.$x

关于javascript - 无法使用 node.js/puppeteer 上传图像文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59513721/

相关文章:

javascript - 预编译模板中的 Hogan.js 部分

javascript - 如何将变量传递给 Puppeteer page.on?

javascript - 检查视口(viewport)中的可见性( puppeteer 师)

javascript - 为什么我必须复制我在 Meteor 的 Package.onTest 中的 Package.onUse 中指定的包?

javascript - 为 IE9 javascript 制作默认主页

javascript - 如何使用特定于 url 的 react native 打开应用程序

javascript - 允许目标事件的默认操作并阻止父事件的默认操作

javascript - express : How to Add Middleware Exclusively to a Large List of Routes in a Router Object?

javascript - 将函数应用于 MongoDB 集合中的所有对象的最有效方法是什么?

node.js - 将await/async 与Puppeteer 函数一起使用时出错