I wrote an helper class which allow me to request the body content from a site that is created by AJAX, for doing so I'm using Puppeteer Sharp. This is the class:
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using PuppeteerSharp;
namespace App.Helpers
{
public class NetworkHelper
{
/// <summary>
/// Get the html of a page waiting for an AJAX call until the selector is visible.
/// </summary>
/// <param name="url">Link needed for execute the request.</param>
/// <param name="selector">Selector to wait.</param>
/// <param name="attempts">Max attempts until request fail.</param>
/// <returns>Contains the html of the requested page.</returns>
public static async Task<string> LoadAndWaitForSelector(Uri url, string selector, int attempts = 5)
{
try
{
//Create new browser page
using (Page page = await Handler.Browser.NewPageAsync())
{
//Navigate on the requested content and wait for selector
await page.GoToAsync(url.ToString(), timeout: 0);
await page.WaitForSelectorAsync(selector); //may throw error for timeout
return await page.GetContentAsync();
}
}
catch (WaitTaskTimeoutException)
{
//there are other attempts, rerty
if (attempts != 0)
{
attempts--;
//add some delay
await Task.Delay(10000);
return await LoadAndWaitForSelector(url, selector, attempts);
}
throw;
}
}
}
Question: Could this class be improved more?
Also, the Browser is static, so each instance use the same browser for avoid memory leak:
public static Browser Browser { get; set; }
the method is called in the following way:
var html = await NetworkHelper.LoadAndWaitForSelector(
new Uri("some url"), "#archive-tables");
thanks.
=5. Then there would be no static state and it would be safe to run it in parallel. \$\endgroup\$_storedUrland_storedSelector. Do you have any other suggestions for improve the class? Thanks. The optional parameter for attempts is a good idea \$\endgroup\$catch(Exception ex) throwis the same as not doing anything and if you use a more specific exception type then only this one will be handled. All others will be rethrown. \$\endgroup\$