Playwright その他の操作
PlaywrightでAPIへリクエスト送信する
PlaywrightでAPIにデータをGET/POST送信する方法です。
サンプル
const pw = require('playwright'); (async () => { const browser = await pw.chromium.launch({ headless: false }); const context = await browser.newContext(); const page = await context.newPage(); //POST const response = await page.request.post("https://web.biz-prog.net/test/post.php", { data: { param1: "data1", param2: 1111 }, headers: { authorization: `Bearer abcdefghijklmnopqrstuvwxyz` } }); console.log(response.status()); console.log((await response.body()).toString()); //GET const response2 = await page.request.get("https://web.biz-prog.net/test/get.php", { params: { param3: "data3", param4: "2222" }, headers: { authorization: `Bearer abcdefghijklmnopqrstuvwxyz` } }); console.log(response2.status()); console.log((await response2.body()).toString()); //await browser.close(); })();
private async void btnPost_Click(object sender, EventArgs e) { using var playwright = await Playwright.CreateAsync(); await using var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions() { Headless = false }); var page = await browser.NewPageAsync(); //POST var data = new Dictionary{ { "param1", "data1" } ,{ "param2", 1111 } }; var head = new Dictionary { { "headers", "Bearer abcdefghijklmnopqrstuvwxyz" } }; var response = await page.APIRequest.PostAsync("https://web.biz-prog.net/test/post.php", new () { DataObject = data, Headers = head }); Debug.WriteLine(response.Status); Debug.WriteLine(System.Text.Encoding.UTF8.GetString(await response.BodyAsync())); //GET var param = new Dictionary { { "param3", "data3" }, { "param4", "data4" } }; response = await page.APIRequest.GetAsync("https://web.biz-prog.net/test/get.php", new() { Params = param, Headers = head }); Debug.WriteLine(response.Status); Debug.WriteLine(System.Text.Encoding.UTF8.GetString(await response.BodyAsync())); }
from playwright.sync_api import sync_playwright, TimeoutError as PlaywrightTimeoutError with sync_playwright() as p: browser = p.chromium.launch(headless=False) page = browser.new_page() # POST response = page.request.post("https://web.biz-prog.net/test/post.php", data = { "param1": "data1", "param2": 1111 }, headers = { "authorization": "Bearer abcdefghijklmnopqrstuvwxyz" } ) print(str(response.status)) print(response.body()) # GET response = page.request.get("https://web.biz-prog.net/test/get.php", params = { "param3": "data3", "param4": "data4" }, headers = { "authorization": "Bearer abcdefghijklmnopqrstuvwxyz" } ) print(str(response.status)) print(response.body()) browser.close()