skip to Main Content

I am unable to upload a file using Playwright as it can’t find a locator for input type

I’m trying to upload a file as below :

 await page.locator('//div/input[@class=xyz]').setInputFiles('Upload_files/CSV Test file.csv');

but the browser is unable to find this locator as the input type as attribute hidden

<input type="file" class="xyz" accept=".jpg,.jpeg,.png,.doc,.docx,.xlsx,.xls,.csv,.pdf" hidden>

2

Answers


  1. Not sure I really like this, but you could remove the hidden attribute first…

    await this.page.evaluate(() => {
        const inputElement = document.querySelector('//div/input[@class=xyz]');
        if (inputElement) {
          inputElement.removeAttribute('hidden');
        }
    });
    
    Login or Signup to reply.
  2. I have had luck finally figured this out:

    You don’t try to find the input. You try to wait for the file chooser to show.

    I have a button#browse that triggers the hidden file input. So this is the code that worked for me:

    const fileChooserPromise = page.waitForEvent('filechooser');
    await page.getByRole('button', { name: 'browse' }).click();
    const fileChooser = await fileChooserPromise;
    await fileChooser.setFiles('./tests/fixures/sig_test.png');
    

    Got this from another reply here in stackoverflow: Playwright: Upload files from non-input element that cannot be used page.setInputFiles?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search