60 lines
2.0 KiB
C#
60 lines
2.0 KiB
C#
using Microsoft.Playwright;
|
|
|
|
namespace FinlyticCore.Services.PlaywrightScrapper;
|
|
|
|
public interface IPlaywrightExecutionService
|
|
{
|
|
/// <summary>
|
|
/// Führt eine Scrape-Aktion auf einer einzelnen Seite innerhalb eines isolierten Kontexts aus.
|
|
/// Der Kontext und die Page werden automatisch nach der Ausführung disposed.
|
|
/// </summary>
|
|
Task<T> ExecuteInPageAsync<T>(
|
|
Func<IPage, Task<T>> action,
|
|
BrowserNewContextOptions? contextOptions = null,
|
|
CancellationToken cancellationToken = default);
|
|
|
|
/// <summary>
|
|
/// Führt eine Multi-Page Scrape-Aktion (z. B. bei Tabs/Popups) in einem Konfiguration-Kontext aus.
|
|
/// </summary>
|
|
Task<T> ExecuteInContextAsync<T>(
|
|
Func<IBrowserContext, Task<T>> action,
|
|
BrowserNewContextOptions? contextOptions = null,
|
|
CancellationToken cancellationToken = default);
|
|
}
|
|
|
|
public class PlaywrightExecutionService : IPlaywrightExecutionService
|
|
{
|
|
private readonly IPlaywrightBrowserFactory _browserFactory;
|
|
|
|
public PlaywrightExecutionService(IPlaywrightBrowserFactory browserFactory)
|
|
{
|
|
_browserFactory = browserFactory;
|
|
}
|
|
|
|
public async Task<T> ExecuteInPageAsync<T>(
|
|
Func<IPage, Task<T>> action,
|
|
BrowserNewContextOptions? contextOptions = null,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
await using var context = await _browserFactory.CreateContextAsync(contextOptions, cancellationToken);
|
|
var page = await context.NewPageAsync();
|
|
|
|
try
|
|
{
|
|
return await action(page);
|
|
}
|
|
finally
|
|
{
|
|
await page.CloseAsync();
|
|
}
|
|
}
|
|
|
|
public async Task<T> ExecuteInContextAsync<T>(
|
|
Func<IBrowserContext, Task<T>> action,
|
|
BrowserNewContextOptions? contextOptions = null,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
await using var context = await _browserFactory.CreateContextAsync(contextOptions, cancellationToken);
|
|
return await action(context);
|
|
}
|
|
} |