簡體   English   中英

無法使用 node.js/puppeteer 上傳圖片文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM