I try to get some DIV by JS script executed in CefSharp and then proced it in C# code. If I geting plain text I can got this from Cef to C# code, but if I try to get whole DIV I got null- this is a issue.
I prepared two JS to get DIV, and string from webpage by css selector. I tested this in Chrome web browser on 4programmers.net page.
JS's:
document.querySelector("#entry-140680").querySelector(".microblog-text").innerText - this return some tekst in console
document.querySelector("#entry-140680") - this return some DIV with childs nodes.
and the result:
result of script in chrome console window
Then I prepared C# code to execute above JS on CefSharp:
public static int Main(string[] args)
{
#if ANYCPU
//Only required for PlatformTarget of AnyCPU
CefRuntime.SubscribeAnyCpuAssemblyResolver();
#endif
const string testUrl = "4programmers.net";
AsyncContext.Run(async delegate
{
var settings = new CefSettings()
{
//By default CefSharp will use an in-memory cache, you need to specify a Cache Folder to persist data
CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache")
};
// Create the CefSharp.OffScreen.ChromiumWebBrowser instance
using (var browser = new ChromiumWebBrowser(testUrl))
{
var initialLoadResponse = await browser.WaitForInitialLoadAsync();
if (!initialLoadResponse.Success)
{
throw new Exception(string.Format("Page load failed with ErrorCode:{0}, HttpStatusCode:{1}", initialLoadResponse.ErrorCode, initialLoadResponse.HttpStatusCode));
}
//Give the browser a little time to render
await Task.Delay(10000);
await browser.EvaluateScriptAsync("window.scrollTo(0,800);");
await Task.Delay(10000);
await browser.EvaluateScriptAsync("document.querySelector(\"#entry-140680\").querySelector(\".microblog-text\").innerText").ContinueWith(x =>
{
var response = x.Result;
if (response.Success && response.Result != null)
{
Console.WriteLine(response.Result == null ? "NULL" : response.Result.ToString());
}
});
Console.WriteLine("--------------");
await browser.EvaluateScriptAsync("document.querySelector(\"#entry-140680\")").ContinueWith(x =>
{
var response = x.Result;
if (response.Success)
{
Console.WriteLine(response.Result == null?"NULL":response.Result.ToString());
}
});
}
Cef.Shutdown();
});
return 0;
}
and the output:
Dziś kilka słów o konferencjach. W dużym skrócie. Jak chcecie Home Office, to zapomnijcie o starych dobrych konferencjach.
https://koziolekweb.pl/2024/02/22/home-office-a-sprawa-konferencji/
#koziolekweb #autopromocja
--------------
NULL
How can I get DIV as object, JSON, string from CefSharp?