【问题标题】:Unable upload image file using node.js/puppeteer无法使用 node.js/puppeteer 上传图像文件
【发布时间】:2020-04-18 04:33:05
【问题描述】:

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

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.

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

【问题讨论】:

  • 您能否详细说明您要做什么?
  • 请提供更多详细信息,例如您尝试使用 xPath 访问的 DOM 或 HTML 以及您尝试上传的文件输入元素。
  • @Trobol 上传图片到我的谷歌账户页面
  • @EdiImanto ...如果您愿意,我可以提供更多 HTML 代码

标签: javascript node.js puppeteer


【解决方案1】:

已解决

事实证明,有问题的图像输入位于 iframe 元素内。经过一番挖掘,我发现如果页面内包含 iframe 元素,则正常的 puppeteer 功能不起作用。这是因为,根据documentation,典型的 puppeteer 函数,如 page.$x、page.$ 和 page.waitFor 实际上是 page.mainFrame().$x、page.mainFrame().$ 和page.mainFrame().waitFor()。因此,这些方法不适用于页面中包含的辅助框架

这是我为克服这个问题所做的。我首先从 src 属性中获得了 iframe 的链接。然后,我创建了一个新页面,并让这个新页面转到此链接。然后,我就可以正常刮了。这是我的代码的解释 sn-p:

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

【讨论】:

    猜你喜欢
    • 2017-12-02
    • 2013-03-25
    • 2022-07-29
    • 1970-01-01
    • 1970-01-01
    • 2021-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多