BotSharp/src/Plugins/BotSharp.Plugin.WebDriver/Drivers/PlaywrightDriver/PlaywrightInstance.cs

185 lines
5.9 KiB
C#
Raw Normal View History

using System.IO;
2024-01-03 19:40:41 +00:00
namespace BotSharp.Plugin.WebDriver.Drivers.PlaywrightDriver;
2024-01-03 04:43:37 +00:00
public class PlaywrightInstance : IDisposable
{
IPlaywright _playwright;
Dictionary<string, IBrowserContext> _contexts = new Dictionary<string, IBrowserContext>();
2024-06-15 04:38:38 +00:00
Dictionary<string, List<IPage>> _pages = new Dictionary<string, List<IPage>>();
/// <summary>
/// ContextId and BrowserContext
/// </summary>
2024-04-09 03:38:56 +00:00
public Dictionary<string, IBrowserContext> Contexts => _contexts;
2024-01-03 04:43:37 +00:00
2024-06-15 04:38:38 +00:00
/// <summary>
/// ContextId and Pages
/// </summary>
public Dictionary<string, List<IPage>> Pages => _pages;
public IPage GetPage(string id, string? pattern = null)
2024-02-06 05:05:52 +00:00
{
return _contexts[id].Pages.LastOrDefault();
2024-02-06 05:05:52 +00:00
}
2024-01-03 04:43:37 +00:00
2024-06-30 13:05:57 +00:00
public async Task<IBrowserContext> GetContext(string ctxId)
2024-01-06 03:24:13 +00:00
{
2024-06-30 13:05:57 +00:00
return _contexts[ctxId];
}
2024-06-30 13:05:57 +00:00
public async Task<IBrowserContext> InitContext(string ctxId, BrowserActionArgs args)
{
2024-06-15 04:38:38 +00:00
if (_contexts.ContainsKey(ctxId))
return _contexts[ctxId];
2024-04-09 03:38:56 +00:00
2024-06-30 13:05:57 +00:00
if (_playwright == null)
{
_playwright = await Playwright.CreateAsync();
}
2024-06-15 04:38:38 +00:00
string tempFolderPath = $"{Path.GetTempPath()}\\playwright\\{ctxId}";
2024-04-09 03:38:56 +00:00
2024-06-15 04:38:38 +00:00
_contexts[ctxId] = await _playwright.Chromium.LaunchPersistentContextAsync(tempFolderPath, new BrowserTypeLaunchPersistentContextOptions
{
2024-06-30 13:05:57 +00:00
Headless = args.Headless,
Channel = "chrome",
2024-06-26 12:48:15 +00:00
ViewportSize = new ViewportSize
{
Width = 1600,
Height = 900
},
2024-06-10 15:51:14 +00:00
IgnoreDefaultArgs =
[
2024-05-17 23:45:18 +00:00
"--enable-automation",
2024-06-10 15:51:14 +00:00
],
2024-06-15 04:38:38 +00:00
Args =
2024-06-10 15:51:14 +00:00
[
2024-04-16 04:48:22 +00:00
"--disable-infobars",
2024-06-10 15:51:14 +00:00
"--test-type"
2024-04-16 04:48:22 +00:00
// "--start-maximized"
2024-06-10 15:51:14 +00:00
]
});
2024-06-15 04:38:38 +00:00
_pages[ctxId] = new List<IPage>();
2024-02-02 04:16:57 +00:00
2024-06-15 04:38:38 +00:00
_contexts[ctxId].Page += async (sender, page) =>
{
2024-06-15 04:38:38 +00:00
_pages[ctxId].Add(page);
page.Close += async (sender, e) =>
{
2024-06-15 04:38:38 +00:00
_pages[ctxId].Remove(e);
Serilog.Log.Information($"Page is closed: {e.Url}");
};
2024-06-15 04:38:38 +00:00
Serilog.Log.Information($"New page is created: {page.Url}");
2024-06-21 18:23:18 +00:00
/*page.Response += async (sender, e) =>
{
Serilog.Log.Information($"Response: {e.Url}");
if (e.Headers.ContainsKey("content-type") && e.Headers["content-type"].Contains("application/json"))
{
var json = await e.JsonAsync();
Serilog.Log.Information(json.ToString());
}
};*/
};
2024-06-15 04:38:38 +00:00
_contexts[ctxId].Close += async (sender, e) =>
{
Serilog.Log.Warning($"Playwright browser context is closed");
2024-06-15 04:38:38 +00:00
_pages.Remove(ctxId);
_contexts.Remove(ctxId);
};
2024-04-09 03:38:56 +00:00
2024-06-15 04:38:38 +00:00
return _contexts[ctxId];
}
2024-06-21 18:23:18 +00:00
public async Task<IPage> NewPage(string ctxId, DataFetched? fetched)
{
2024-06-30 13:05:57 +00:00
var context = await GetContext(ctxId);
var page = await context.NewPageAsync();
// 许多网站为了防止信息被爬取,会添加一些防护手段。其中之一是检测 window.navigator.webdriver 属性。
// 当使用 Playwright 打开浏览器时,该属性会被设置为 true从而被网站识别为自动化工具。通过以下方式屏蔽这个属性让网站无法识别是否使用了 Playwright
var js = @"Object.defineProperties(navigator, {webdriver:{get:()=>false}});";
await page.AddInitScriptAsync(js);
2024-06-21 18:23:18 +00:00
if (fetched != null)
{
page.Response += async (sender, e) =>
{
if (e.Headers.ContainsKey("content-type") &&
e.Headers["content-type"].Contains("application/json") &&
2024-07-21 00:57:54 +00:00
(e.Request.ResourceType == "fetch" || e.Request.ResourceType == "xhr"))
2024-06-21 18:23:18 +00:00
{
2024-07-21 00:57:54 +00:00
Serilog.Log.Information($"{e.Request.Method}: {e.Url}");
JsonElement? json = null;
2024-07-08 18:26:17 +00:00
try
{
2024-07-17 12:05:16 +00:00
if (e.Status == 200 && e.Ok)
{
json = await e.JsonAsync();
}
else
{
Serilog.Log.Warning($"Response status: {e.Status} {e.StatusText}, OK: {e.Ok}");
}
2024-07-21 00:57:54 +00:00
fetched(e.Url.ToLower(), e.Request?.PostData ?? string.Empty, JsonSerializer.Serialize(json));
2024-07-08 18:26:17 +00:00
}
catch(Exception ex)
{
Serilog.Log.Error(ex.ToString());
}
2024-06-21 18:23:18 +00:00
}
};
}
2024-06-15 04:38:38 +00:00
return page;
}
2024-06-15 04:38:38 +00:00
/// <summary>
/// Wait page and network until timeout in seconds
/// </summary>
/// <param name="ctxId"></param>
/// <param name="timeout">seconds</param>
/// <returns></returns>
public async Task Wait(string ctxId, int timeout = 60)
{
2024-06-15 04:38:38 +00:00
foreach (var page in _pages[ctxId])
{
2024-02-15 21:55:50 +00:00
await page.WaitForLoadStateAsync(LoadState.DOMContentLoaded);
2024-06-15 04:38:38 +00:00
await page.WaitForLoadStateAsync(LoadState.NetworkIdle, new PageWaitForLoadStateOptions
{
Timeout = 1000 * timeout
});
}
2024-02-12 21:49:18 +00:00
await Task.Delay(100);
}
2024-06-15 04:38:38 +00:00
public async Task Close(string ctxId)
{
2024-06-15 04:38:38 +00:00
if (_contexts.ContainsKey(ctxId))
{
2024-06-15 04:38:38 +00:00
await _contexts[ctxId].CloseAsync();
2024-01-06 03:24:13 +00:00
}
}
2024-06-15 04:38:38 +00:00
public async Task CloseCurrentPage(string ctxId)
2024-04-09 03:38:56 +00:00
{
2024-06-15 04:38:38 +00:00
var pages = _pages[ctxId].ToArray();
for (var i = 0; i < pages.Length; i++)
2024-04-09 03:38:56 +00:00
{
2024-06-22 22:04:03 +00:00
var page = _pages[ctxId].FirstOrDefault();
if (page != null)
{
await page.CloseAsync();
}
2024-04-09 03:38:56 +00:00
}
}
2024-01-03 04:43:37 +00:00
public void Dispose()
{
_contexts.Clear();
2024-05-17 23:45:18 +00:00
_playwright?.Dispose();
2024-01-03 04:43:37 +00:00
}
}