如何使用Python版Playwright发送PUT请求上传multipart/form-data?
使用Python Playwright模拟curl的multipart/form-data PUT文件上传
要复现你给出的curl命令效果,关键是在Playwright的multipart参数中,将文件字段配置为包含路径、文件名和MIME类型的嵌套字典,而非拆分多个独立键。
同步版本代码
from playwright.sync_api import sync_playwright with sync_playwright() as p: browser = p.chromium.launch() context = browser.new_context() # 发送PUT请求,配置multipart文件字段 response = context.request.put( url="localhost:8080", multipart={ "file": { "path": "./test.zip", # 对应curl中的@test.zip "filename": "test.zip", # 显式指定文件名 "content_type": "application/x-zip-compressed" # 设置文件MIME类型 } } ) print(f"响应状态码: {response.status}") browser.close()
异步版本代码
如果你使用异步API,写法如下:
import asyncio from playwright.async_api import async_playwright async def main(): async with async_playwright() as p: browser = await p.chromium.launch() context = await browser.new_context() response = await context.request.put( url="localhost:8080", multipart={ "file": { "path": "./test.zip", "filename": "test.zip", "content_type": "application/x-zip-compressed" } } ) print(f"响应状态码: {response.status}") await browser.close() asyncio.run(main())
关键说明
multipart字典的顶层键file对应curl命令中的表单字段名file- 嵌套字典的
path指定本地文件的路径,等价于curl中的@test.zip filename和content_type分别对应curl里的filename=test.zip和type=application/x-zip-compressed,这两个参数是可选的,省略时Playwright会自动从文件路径推断文件名和MIME类型- 不要将这些属性拆分为独立的顶层键(比如单独设置
filename键),否则会生成多个独立的表单部分,导致请求格式错误
内容的提问来源于stack exchange,提问作者daviewales
相关产品推荐
相关产品推荐

