[英]Unable upload image file using 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 功能将不起作用。 这是因为,根据文档,典型的 puppeteer 函数如 page.$x、page.$ 和 page.waitFor 实际上是 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.