How to use ElementHandle class of PuppeteerSharp package

Best Puppeteer-sharp code snippet using PuppeteerSharp.ElementHandle

ShiftSearchClient.cs

Source:ShiftSearchClient.cs Github

copy

Full Screen

...35 {36 var page = await GetPage();37 Thread.Sleep(1000);38 int attempt = 1;39 ElementHandle? handle = null;40 while (handle == null && attempt <= 3)41 {42 if (attempt > 1)43 {44 Console.WriteLine( $"Could not find div with xPath {xPath} on page {page.Url}. Trying again: attempt {attempt}");45 Thread.Sleep(attempt * 1000);46 }47 handle = await GetElement( page, xPath);48 attempt++;49 }50 if (handle == null)51 {52 Log.Error( $"Could not find div with xPath {xPath} on page {page.Url}!");53 // TODO Throw exception54 return "";55 }56 return await page.EvaluateFunctionAsync<string>("e => e.textContent", handle);57 }58 protected async Task<ElementHandle?> GetElementWithContent(Page page, string elementType, string content)59 {60 string xPathMatch = string.Format("//{0}[contains(., '{1}')]", elementType, content);61 return await GetElement(page, xPathMatch);62 }63 public async Task<bool> GoToPage(string url)64 {65 Console.WriteLine($"Navigating to page {url}");66 if (Browser == null)67 {68 Browser = await StartBrowser();69 }70 Page page = await GetPage();71 try72 {73 if (page.Url == url)74 {75 await page.ReloadAsync();76 return page.Url == url;77 }78 await page.GoToAsync(url);79 return page.Url == url;80 }81 catch (Exception ex)82 {83 Log.Error($"Error loading page {url}, {ex}");84 return false;85 }86 }87 protected async Task<ElementHandle?> GetElement(Page page, string xPathMatch)88 {89 ElementHandle[] elementHandles = await page.XPathAsync(xPathMatch);90 List<ElementHandle> visibleHandles = new List<ElementHandle>();91 foreach (ElementHandle handle in elementHandles)92 {93 if (await handle.IsIntersectingViewportAsync())94 {95 visibleHandles.Add(handle);96 }97 }98 if (visibleHandles.Count == 0)99 {100 return null;101 }102 if (visibleHandles.Count > 1)103 {104 Log.Warning(string.Format("Multiple elements found with xPath {0}", xPathMatch));105 }...

Full Screen

Full Screen

PuppeteerSharpRepoSpecs.cs

Source:PuppeteerSharpRepoSpecs.cs Github

copy

Full Screen

...23 {24 Page page = Browser.NewPageAsync().Await();25 page.GoToAsync("https://github.com/").Await();26 page.QuerySelectorAsync("h1").ShouldHaveContent("Where the world builds software");27 ElementHandle input = page.QuerySelectorAsync("input.header-search-input").Await();28 if (input.IsHidden()) page.ClickAsync(".octicon-three-bars").Await();29 page.TypeAsync("input.header-search-input", "Puppeteer Sharp").Await();30 page.Keyboard.PressAsync("Enter").Await();31 page.WaitForNavigationAsync().Await();32 ElementHandle[] repositories = page.QuerySelectorAllAsync(".repo-list-item").Await();33 repositories.Length.ShouldBeGreaterThan(0);34 var repository = repositories.First();35 repository.ShouldHaveContent("hardkoded/puppeteer-sharp");36 ElementHandle text = repository.QuerySelectorAsync("p").Await();37 text.ShouldHaveContent("Headless Chrome .NET API");38 ElementHandle link = repository.QuerySelectorAsync("a").Await();39 link.ClickAsync().Await();40 page.WaitForNavigationAsync().Await();41 page.QuerySelectorAsync("article > h1").ShouldHaveContent("Puppeteer Sharp");42 page.Url.ShouldEqual("https://github.com/hardkoded/puppeteer-sharp");43 };44 }45 class When_viewing_the_repo_on_GitHub46 {47 It should_have_successful_build_status = () =>48 {49 Page page = Browser.NewPageAsync().Await();50 page.GoToAsync("https://github.com/hardkoded/puppeteer-sharp").Await();51 ElementHandle build = page.QuerySelectorAsync("img[alt='Build status']").Await();52 build.ClickAsync().Await();53 page.WaitForNavigationAsync(new NavigationOptions { WaitUntil = new[] { WaitUntilNavigation.Networkidle0 } }).Await();54 ElementHandle success = page.QuerySelectorAsync(".project-build.project-build-status.success").Await();55 success.ShouldExist();56 };57 It should_be_up_to_date_with_the_Puppeteer_version = () =>58 {59 Page page = Browser.NewPageAsync().Await();60 page.GoToAsync("https://github.com/hardkoded/puppeteer-sharp").Await();61 var puppeteerSharpVersion = GetLatestReleaseVersion();62 page.GoToAsync("https://github.com/puppeteer/puppeteer").Await();63 var puppeteerVersion = GetLatestReleaseVersion();64 puppeteerSharpVersion.ShouldEqual(puppeteerVersion);65 string GetLatestReleaseVersion()66 {67 ElementHandle latest = page.QuerySelectorWithContentAsync("a[href*='releases'] span", @"v\d+\.\d\.\d").Await();68 return latest.TextContent();69 }70 };71 }72 }73}...

Full Screen

Full Screen

IPuppeteerBrowser.cs

Source:IPuppeteerBrowser.cs Github

copy

Full Screen

...13 Task<string> GetPageContent(string stringUrl, params WaitUntilNavigation[] waitUntilNavigations);14 Task<Page> GetPage(string url, TimeSpan? timeoutPageLoad, params WaitUntilNavigation[] waitUntilNavigations);15 Task<Page[]> GetPages();16 Task<Page> WaitGetPage(Page page, string selector, string targetId);17 Task<Page> ClickAndGetPage(ElementHandle element, string targetId);18 Task<Page> ClickAndGetPage(ElementHandle element, string targetId, WaitForOptions waitForOptions);19 Task<string> GetContentAsync(Page page);20 Task ClickAsync(Page page, string clickPlace, ClickOptions clickOptions = null);21 Task<string> GetFramePage(string iframeSrc);22 Task<string> GetFramePage(Page page, string frameName);23 Task<string> GetVideoAdsOnUrl(Page page, string xPath);24 Task<string> GetScrolledPage(string videoUrl, int maxScroll, params WaitUntilNavigation[] waitUntilNavigations);25 Task<string> GetPagePermission(Page page, string permissionName);26 Task<string> ClickButtonForContinue(Page page, string buttonXPath, string adUrl,27 params WaitUntilNavigation[] waitUntilNavigations);28 /// <summary>29 /// Returns IpDetails by the specified url30 /// </summary>31 /// <param name="ipFetcherUrl">The ip details provider url.</param>32 /// <returns>The instance of <see cref="IpDetails"></see></returns>...

Full Screen

Full Screen

ProxyFactoryTests.cs

Source:ProxyFactoryTests.cs Github

copy

Full Screen

...45 var elementHandles = await Page.QuerySelectorAllAsync("div");46 var result = ProxyFactory.ElementObjectArray(typeof(FakeElementObject), Page, elementHandles);47 Assert.NotEmpty(result);48 Assert.All(result.Cast<ElementObject>(), x => Assert.IsAssignableFrom<FakeElementObject>(x));49 result = ProxyFactory.ElementObjectArray(typeof(FakeElementObject), Page, new ElementHandle[0]);50 Assert.Empty(result);51 }52 }53}...

Full Screen

Full Screen

PageObjects.cs

Source:PageObjects.cs Github

copy

Full Screen

...6{7 public class GitHubStartPage : PageObject8 {9 [Selector("h1")]10 public virtual Task<ElementHandle> Heading { get; }11 [Selector(".HeaderMenu")]12 public virtual Task<GitHubHeaderMenu> HeaderMenu { get; }13 }14 public class GitHubHeaderMenu : ElementObject15 {16 [Selector("input.header-search-input")]17 public virtual Task<ElementHandle> SearchInput { get; }18 public async Task<GitHubSearchPage> Search(string text)19 {20 var input = await SearchInput;21 if (await input.IsHiddenAsync()) await Page.ClickAsync(".octicon-three-bars");22 await input.TypeAsync(text);23 await input.PressAsync(Key.Enter);24 return await Page.WaitForNavigationAsync<GitHubSearchPage>();25 }26 }27 public class GitHubSearchPage : PageObject28 {29 [Selector(".repo-list-item")]30 public virtual Task<GitHubRepoListItem[]> RepoListItems { get; }31 }32 public class GitHubRepoListItem : ElementObject33 {34 [Selector("a")]35 public virtual Task<ElementHandle> Link { get; }36 [Selector("p")]37 public virtual Task<ElementHandle> Text { get; }38 }39 public class GitHubRepoPage : PageObject40 {41 [Selector("article > h1")]42 public virtual Task<ElementHandle> Heading { get; }43 [Selector("img[alt='Build status']")]44 public virtual Task<ElementHandle> BuildStatusBadge { get; }45 public async Task<string> GetLatestReleaseVersion()46 {47 var latest = await Page.QuerySelectorWithContentAsync("a[href*='releases'] span", @"v\d+\.\d\.\d");48 return await latest.TextContentAsync();49 }50 }51 public class AppVeyorBuildPage : PageObject52 {53 public async Task<bool> Success()54 {55 var success = await Page.QuerySelectorAsync(".project-build.project-build-status.success");56 return success.Exists();57 }58 }...

Full Screen

Full Screen

ElementObject.cs

Source:ElementObject.cs Github

copy

Full Screen

...11 /// <![CDATA[12 /// public class BarElementObject : ElementObject13 /// {14 /// [Selector("#foo")]15 /// public virtual Task<ElementHandle> SelectorForElementHandle { get; }16 ///17 /// [Selector(".bar")]18 /// public virtual Task<ElementHandle[]> SelectorForElementHandleArray { get; }19 ///20 /// [Selector("#foo")]21 /// public virtual Task<FooElementObject> SelectorForElementObject { get; }22 ///23 /// [Selector(".bar")]24 /// public virtual Task<BarElementObject[]> SelectorForElementObjectArray { get; }25 ///26 /// [XPath("//div")]27 /// public virtual Task<ElementHandle[]> XPathForElementHandleArray { get; }28 ///29 /// [XPath("//div")]30 /// public virtual Task<FooElementObject[]> XPathForElementObjectArray { get; }31 /// }32 /// ]]>33 /// </code>34 /// </example>35 public abstract class ElementObject36 {37 /// <summary>38 /// The <c>PuppeteerSharp</c> page.39 /// </summary>40 public Page Page { get; private set; }41 /// <summary>42 /// The <c>PuppeteerSharp</c> element handle.43 /// </summary>44 public ElementHandle Element { get; private set; }45 internal void Initialize(Page page, ElementHandle element)46 {47 Page = page;48 Element = element;49 }50 }51}...

Full Screen

Full Screen

HomePage.cs

Source:HomePage.cs Github

copy

Full Screen

...10{11 public class HomePage : PageObject12 {13 [Selector(".slider ul li a")]14 public virtual Task<ElementHandle[]> MovieElements { get; set; }15 public async Task<List<string>> GetMovieDataList()16 {17 var aEls = await MovieElements;18 var linkAddress = new List<string>();19 foreach (var item in aEls)20 {21 var attrVal = await item.GetAttributeAsync("href");22 linkAddress.Add(attrVal);23 }24 //var tempPage = await Page.Browser.NewPageAsync();25 //var result = new List<MovieModel>();26 //foreach (var address in linkAddress)27 //{28 // var movie = await tempPage.GoToAsync<Movie>(address,...

Full Screen

Full Screen

HandleExtensions.cs

Source:HandleExtensions.cs Github

copy

Full Screen

...4namespace Wasari.Puppeteer5{6 public static class HandleExtensions7 {8 public static async Task<ElementHandle> SingleOrDefaultXPathAsync(this Page page,9 string xpath)10 {11 var handles = await page.XPathAsync(xpath);12 return handles.SingleOrDefault();13 }14 15 public static async Task<ElementHandle> SingleOrDefaultXPathAsync(this ElementHandle elementHandle,16 string xpath)17 {18 var handles = await elementHandle.XPathAsync(xpath);19 return handles.SingleOrDefault();20 }21 public static async Task<T> GetPropertyValue<T>(this JSHandle elementHandle, string property)22 {23 await using var propertyAsync = await elementHandle.GetPropertyAsync(property);24 if (propertyAsync != null)25 return await propertyAsync.JsonValueAsync<T>();26 return default;27 }28 }29}...

Full Screen

Full Screen

ElementHandle

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2using System;3using System.Threading.Tasks;4{5 {6 static async Task Main(string[] args)7 {8 {9 ExecutablePath = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"10 };11 using (var browser = await Puppeteer.LaunchAsync(options))12 {13 using (var page = await browser.NewPageAsync())14 {15 var search = await page.QuerySelectorAsync("input[name='q']");16 await search.TypeAsync("PuppeteerSharp");17 await search.PressAsync("Enter");18 await page.WaitForNavigationAsync();19 var element = await page.QuerySelectorAsync("h3 > a");20 var href = await element.GetPropertyAsync("href");21 Console.WriteLine(href.ToString());22 }23 }24 }25 }26}

Full Screen

Full Screen

ElementHandle

Using AI Code Generation

copy

Full Screen

1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using PuppeteerSharp;7{8 {9 static void Main(string[] args)10 {11 MainAsync().Wait();12 }13 static async Task MainAsync()14 {15 {16 };17 using (var browser = await Puppeteer.LaunchAsync(options))18 {19 using (var page = await browser.NewPageAsync())20 {21 var element = await page.QuerySelectorAsync("input[name='q']");22 await element.TypeAsync("Hello World");23 await element.PressAsync("Enter");24 await page.WaitForNavigationAsync();25 Console.WriteLine(page.Url);26 }27 }28 }29 }30}31using System;32using System.Collections.Generic;33using System.Linq;34using System.Text;35using System.Threading.Tasks;36using PuppeteerSharp;37{38 {39 static void Main(string[] args)40 {41 MainAsync().Wait();42 }43 static async Task MainAsync()44 {45 {46 };47 using (var browser = await Puppeteer.LaunchAsync(options))48 {49 using (var page = await browser.NewPageAsync())50 {51 var element = await page.QuerySelectorAsync("input[name='q']");52 await element.TypeAsync("Hello World");53 await element.PressAsync("Enter");54 await page.WaitForNavigationAsync();55 Console.WriteLine(page.Url);56 }57 }58 }59 }60}61using System;62using System.Collections.Generic;63using System.Linq;64using System.Text;65using System.Threading.Tasks;66using PuppeteerSharp;67{68 {69 static void Main(string[] args)70 {71 MainAsync().Wait();72 }73 static async Task MainAsync()74 {75 {76 };77 using (var browser = await

Full Screen

Full Screen

ElementHandle

Using AI Code Generation

copy

Full Screen

1using PuppeteerSharp;2var options = new LaunchOptions { Headless = false };3var browser = await Puppeteer.LaunchAsync(options);4var page = await browser.NewPageAsync();5var element = await page.QuerySelectorAsync("#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input");6await element.TypeAsync("PuppeteerSharp");7await browser.CloseAsync();8using PuppeteerSharp;9var options = new LaunchOptions { Headless = false };10var browser = await Puppeteer.LaunchAsync(options);11var page = await browser.NewPageAsync();12var element = await page.QuerySelectorAsync("#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input");13await element.TypeAsync("PuppeteerSharp");14await browser.CloseAsync();15using PlaywrightSharp;16var playwright = await Playwright.CreateAsync();17var browser = await playwright.Chromium.LaunchAsync();18var context = await browser.NewContextAsync();19var page = await context.NewPageAsync();20var element = await page.QuerySelectorAsync("#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input");21await element.TypeAsync("PlaywrightSharp");22await browser.CloseAsync();

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful