You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Playwright无法通过img标签的file://访问本地文件求助

Playwright加载本地file://图片不显示的解决方法

原因

Playwright默认的浏览器安全策略会阻止从非file://源(通过setContent创建的页面origin为null)加载本地file://资源,这是跨源安全限制导致的。

解决方案1:禁用Web安全(仅测试环境使用)

在创建浏览器上下文时,添加webSecurity: false配置,关闭跨源安全检查,即可加载本地file://资源。注意file://路径必须是完整绝对路径(比如Mac上的file:///Users/你的用户名/resources/image.png),不能用相对路径。

修改后的代码:

async function screenShot() {
     const browser = await chromium.launch();
    // 添加webSecurity: false关闭跨源安全限制
    const context = await browser.newContext({ webSecurity: false });
    const page = await context.newPage();
    await page.setViewportSize({ width:200, height:200 });
    await page.setContent(`
<html><body>
        <div id="container">
        <h1>HELLO</h1>
                <img src="file:///Users/你的用户名/resources/image.png" />
            </div></body>
            </html>
    `)

    await page.locator("#container").screenshot({ path: 'screenshot.png' });

    await context.close();
    await browser.close();
}

解决方案2:将图片转为Base64嵌入HTML(更安全)

不需要修改安全设置,直接把本地图片读取为Base64字符串嵌入HTML的img标签中,彻底避免跨源问题,适合生产环境使用。

示例代码:

const fs = require('fs');
const path = require('path');

async function screenShot() {
     const browser = await chromium.launch();
    const context = await browser.newContext();
    const page = await context.newPage();
    await page.setViewportSize({ width:200, height:200 });

    // 读取本地图片并转为Base64
    const imagePath = path.resolve(__dirname, 'resources/image.png');
    const imageBase64 = fs.readFileSync(imagePath, 'base64');
    const imgSrc = `data:image/png;base64,${imageBase64}`;

    await page.setContent(`
<html><body>
        <div id="container">
        <h1>HELLO</h1>
                <img src="${imgSrc}" />
            </div></body>
            </html>
    `)

    await page.locator("#container").screenshot({ path: 'screenshot.png' });

    await context.close();
    await browser.close();
}

解决方案3:加载本地HTML文件

把HTML内容保存为本地文件,通过page.goto加载该file://协议的文件,此时页面origin为file://,可正常加载同目录或相对路径的本地图片。

  1. 保存本地HTML文件(比如test.html):
<html><body>
    <div id="container">
    <h1>HELLO</h1>
            <img src="./resources/image.png" /> <!-- 相对路径基于HTML文件位置 -->
        </div></body>
        </html>
  1. 修改代码:
async function screenShot() {
     const browser = await chromium.launch();
    const context = await browser.newContext();
    const page = await context.newPage();
    await page.setViewportSize({ width:200, height:200 });
    // 加载本地HTML文件
    await page.goto('file:///Users/你的用户名/test.html');

    await page.locator("#container").screenshot({ path: 'screenshot.png' });

    await context.close();
    await browser.close();
}

内容的提问来源于stack exchange,提问作者The Prenx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:15:28