Ⅰ. はじめに
タイトルの通り「Playwright(C#)でファイルをアップロードする方法」です。
Ⅱ. 手順
1. Webサーバー側サンプルプログラムを書く
# pip install flask==2.2.3 from flask import Flask, request, Response app = Flask(__name__) @app.route('/', methods=['GET']) def index(): return ''' <form id="form001" action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file001"> <input type="submit"> </form> ''' @app.route('/upload', methods=['POST']) def upload(): # カレントディレクトリにファイルを保存する file = request.files['file001'] file.save(file.filename) return Response(status=204) if __name__ == '__main__': app.run(host='127.0.0.1', port=8000, threaded=True, debug=True)
2. Playwright側サンプルプログラムを書く
// dotnet add package Microsoft.Playwright --version 1.31.1 using Microsoft.Playwright; using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = true }); var page = await browser.NewPageAsync(); await page.GotoAsync($"http://127.0.0.1:8000"); await page.WaitForSelectorAsync("#form001"); var fileChooser = await page.RunAndWaitForFileChooserAsync(async () => { await page.Locator("input[name='file001']").ClickAsync(); }); await fileChooser.SetFilesAsync("input.txt"); var formElement = await page.QuerySelectorAsync("#form001"); if (formElement != null) { await formElement.EvaluateAsync("x => x.submit()"); }
実行結果
省略