BotSharp/src/Plugins/BotSharp.Plugin.WebDriver/Drivers/PlaywrightDriver/PlaywrightWebDriver.ClickElement.cs

73 lines
2.4 KiB
C#
Raw Normal View History

2024-02-02 04:16:57 +00:00
using Microsoft.Extensions.Logging;
using System.Text.RegularExpressions;
namespace BotSharp.Plugin.WebDriver.Drivers.PlaywrightDriver;
public partial class PlaywrightWebDriver
{
2024-02-06 05:05:52 +00:00
public async Task<bool> ClickElement(BrowserActionParams actionParams)
2024-02-02 04:16:57 +00:00
{
await _instance.Wait(actionParams.ConversationId);
2024-02-02 04:16:57 +00:00
2024-02-14 00:19:44 +00:00
var page = _instance.GetPage(actionParams.ConversationId);
ILocator locator = default;
int count = 0;
2024-02-02 04:16:57 +00:00
// Retrieve the page raw html and infer the element path
2024-02-14 00:19:44 +00:00
if (!string.IsNullOrEmpty(actionParams.Context.ElementText))
{
2024-02-14 00:19:44 +00:00
var regexExpression = actionParams.Context.MatchRule.ToLower() switch
{
"startwith" => $"^{actionParams.Context.ElementText}",
"endwith" => $"{actionParams.Context.ElementText}$",
"contains" => $"{actionParams.Context.ElementText}",
_ => $"^{actionParams.Context.ElementText}$"
};
var regex = new Regex(regexExpression, RegexOptions.IgnoreCase);
locator = page.GetByText(regex);
count = await locator.CountAsync();
// try placeholder
if (count == 0)
{
locator = page.GetByPlaceholder(regex);
count = await locator.CountAsync();
}
}
// try attribute
if (count == 0 && !string.IsNullOrEmpty(actionParams.Context.AttributeName))
2024-02-02 04:16:57 +00:00
{
2024-02-14 00:19:44 +00:00
locator = page.Locator($"[{actionParams.Context.AttributeName}='{actionParams.Context.AttributeValue}']");
count = await locator.CountAsync();
2024-02-02 04:16:57 +00:00
}
if (count == 0)
{
2024-02-06 05:05:52 +00:00
_logger.LogError($"Can't locate element by keyword {actionParams.Context.ElementText}");
}
else if (count == 1)
{
2024-02-15 20:37:42 +00:00
// var tagName = await locator.EvaluateAsync<string>("el => el.tagName");
2024-02-14 00:19:44 +00:00
await locator.ClickAsync();
2024-02-06 05:05:52 +00:00
// Triggered ajax
await _instance.Wait(actionParams.ConversationId);
2024-02-06 05:05:52 +00:00
return true;
2024-02-02 04:16:57 +00:00
}
else if (count > 1)
{
2024-02-06 05:05:52 +00:00
_logger.LogWarning($"Multiple elements are found by keyword {actionParams.Context.ElementText}");
2024-02-14 00:19:44 +00:00
var all = await locator.AllAsync();
2024-02-08 23:22:43 +00:00
foreach (var element in all)
{
var content = await element.TextContentAsync();
_logger.LogWarning(content);
}
2024-02-02 04:16:57 +00:00
}
2024-02-06 05:05:52 +00:00
return false;
2024-02-02 04:16:57 +00:00
}
}