Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. public class NetworkHelper
  2. {
  3. /// <summary>
  4. /// Max attempts after a failed request.
  5. /// </summary>
  6. private static int _failedAttempts = 10;
  7.  
  8. /// <summary>
  9. /// Get the html of a page waiting for a specific selector created by an ajax request.
  10. /// </summary>
  11. /// <param name="url">Link of the page.</param>
  12. /// <param name="selector">Selector to wait.</param>
  13. /// <returns>Html of the web page.</returns>
  14. public static async Task<string> LoadAndWaitForSelector(Uri url, string selector)
  15. {
  16. var browser = await Puppeteer.LaunchAsync(new LaunchOptions
  17. {
  18. Headless = true,
  19. ExecutablePath = Environment.GetEnvironmentVariable("CHROME_PATH"),
  20. });
  21.  
  22. try
  23. {
  24. using (Page page = await browser.NewPageAsync())
  25. {
  26. await page.GoToAsync(url.ToString());
  27. await page.WaitForSelectorAsync(selector);
  28. return await page.GetContentAsync();
  29. }
  30. }
  31. catch (Exception ex)
  32. {
  33. //Scale the attempts and retry, server could be busy or the connection goes offline.
  34. if (_failedAttempts != 0)
  35. {
  36. _failedAttempts--;
  37. await Task.Delay(15000);
  38. }
  39. else
  40. {
  41. throw ex;
  42. }
  43.  
  44. return await LoadAndWaitForSelector(url, selector);
  45. }
  46. }
  47. }
  48.  
  49. var browser = await Puppeteer.LaunchAsync(new LaunchOptions
  50. {
  51. Headless = true,
  52. ExecutablePath = Environment.GetEnvironmentVariable("CHROME_PATH"),
  53. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement