到目前为止,我已经尝试了两件事。
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/