How to use SetViewportAsync method of PuppeteerSharp.Page class

Best Puppeteer-sharp code snippet using PuppeteerSharp.Page.SetViewportAsync

Run Puppeteer-sharp automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

WebScraper.cs

Source: WebScraper.cs Github

copy
1using System;
2using System.Drawing;
3using System.IO;
4using System.Threading.Tasks;
5using PuppeteerSharp;
6using PuppeteerSharp.Input;
7
8namespace ScraperionFramework
9{
10    /// <summary>
11    /// Web scraper class.
12    /// This class handles all interaction with chromium.
13    /// </summary>
14    public class WebScraper : IDisposable
15    {
16        private readonly Browser m_browser;
17        private readonly Page m_page;
18        private decimal m_MouseX = 0;
19        private decimal m_MouseY = 0;
20
21        /// <summary>
22        /// Defualt agent string this library uses. Simulates Chrome installed on windows 10.
23        /// </summary>
24        public static readonly string DefaultAgent =
25            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36";
26
27        /// <summary>
28        /// Constructor.
29        /// </summary>
30        /// <param name="headless">Set to false to show chromium window.</param>
31        /// <param name="agent">Agent to use when accessing pages. Uses DefaultAgent if non is set.</param>
32        public WebScraper(bool headless = true, string agent = "")
33        {
34
35            if (agent == "")
36                agent = DefaultAgent;
37
38
39            var ops = new BrowserFetcherOptions
40            {
41                Path = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\scraperion\\browser"
42            };
43
44            (new BrowserFetcher(ops).DownloadAsync(BrowserFetcher.DefaultRevision)).Wait();
45
46            var browser = Puppeteer.LaunchAsync(new LaunchOptions
47            {
48                Headless = headless,
49                IgnoreHTTPSErrors = true,
50
51            });
52
53            browser.Wait();
54            m_browser = browser.Result;
55
56
57            var page = m_browser.NewPageAsync();
58            page.Wait();
59            m_page = page.Result;
60
61            m_page.Error += (s, e) => {
62                Console.WriteLine("Error:" + e.ToString());
63            };
64
65            m_page.PageError += (s, e) =>
66            {
67                Console.WriteLine("Error:" + e.ToString());
68            };
69
70            m_page.Console += (s, e) => { Console.WriteLine(e.Message.Text); };
71
72            m_page.SetUserAgentAsync(agent).Wait();
73        }
74
75        /// <summary>
76        /// Set username and password to authenticate against web pages with.
77        /// </summary>
78        /// <param name="username">Username to authenticate with</param>
79        /// <param name="password">Password to autrhenticate with.</param>
80        public void SetAuth(string username, string password)
81        {
82            SetAuthAsync(username, password).Wait();
83        }
84
85        private async Task SetAuthAsync(string username, string password)
86        {
87            await m_page.AuthenticateAsync(new Credentials {Username = username, Password = password});
88        }
89
90        /// <summary>
91        /// Sets the view port size of the page.
92        /// </summary>
93        /// <param name="width">Width of the page in pixels.</param>
94        /// <param name="height">Height of page in pixels.</param>
95        public void SetViewPort(int width, int height)
96        {
97            SetViewPortAsync(width, height).Wait();
98        }
99
100        private async Task SetViewPortAsync(int width, int height)
101        {
102            await m_page.SetViewportAsync(new ViewPortOptions
103            {
104                Width = width,
105                Height = height
106            });
107        }
108
109        /// <summary>
110        /// Gets or sets the url the page is currently at.
111        /// </summary>
112        public string Url
113        {
114            get => m_page.Url;
115            set
116            {
117                try
118                {
119                    m_page.GoToAsync(value).Wait();
120                }
121                catch (Exception e)
122                {
123                    Console.WriteLine(e);
124                }
125            }
126        }
127
128        /// <summary>
129        /// Executes a javascript expression on page.
130        /// This is simuilar to typing a command in the java console.
131        /// </summary>
132        /// <param name="script">Expression to run.</param>
133        /// <returns>Json of executed result.</returns>
134        public string Exec(string script)
135        {
136            var result = ExecAsync(script);
137            result.Wait();
138
139            return result.Result;
140        }
141
142        private async Task<string> ExecAsync(string script)
143        {
144
145           var data = await m_page.EvaluateExpressionAsync(script);
146
147            return (string)data.ToString();
148
149        }
150        /// <summary>
151        /// Takes a screenshot of the target page.
152        /// </summary>
153        /// <returns>Bitmap image containing screenshot.</returns>
154        public Bitmap SnapshotBitmap()
155        {
156            var result = SnapshotBitmapAsync();
157            result.Wait();
158            return result.Result;
159        }
160
161        private async Task<Bitmap> SnapshotBitmapAsync()
162        {
163            var data = await m_page.ScreenshotStreamAsync();
164            var image = new Bitmap(data);
165            data.Dispose();
166
167            return image;
168        }
169
170        /// <summary>
171        /// Simulates key presses on page.
172        /// </summary>
173        /// <param name="text">Text to send to page.</param>
174        public void SendKeys(string text)
175        {
176            SendKeysAsync(text).Wait();
177        }
178
179        private async Task SendKeysAsync(string text)
180        {
181            await m_page.Keyboard.TypeAsync(text);
182        }
183
184        /// <summary>
185        /// Simulates moving the mouse on the page.
186        ///
187        /// Note: this does not move the system mouse.
188        /// </summary>
189        /// <param name="x">X coordinates to move mouse to.</param>
190        /// <param name="y">Y coordinates to move mouse to.</param>
191        public void MoveMouse(decimal x, decimal y)
192        {
193            MoveMouseAsync(x, y).Wait();
194        }
195
196        private async Task MoveMouseAsync(decimal x, decimal y)
197        {
198            await m_page.Mouse.MoveAsync(x, y);
199            m_MouseX = x;
200            m_MouseY = y;
201        }
202
203        /// <summary>
204        /// Simulates a mouse click on page.
205        /// </summary>
206        /// <param name="button">Mouse button to simulate.</param>
207        public void MouseClick(MouseButton button)
208        {
209            MouseClickAsync(button).Wait();
210        }
211
212        private async Task MouseClickAsync(MouseButton button)
213        {
214            await m_page.Mouse.ClickAsync(m_MouseX, m_MouseY, new ClickOptions{ Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });
215        }
216
217        /// <summary>
218        /// Simulates a mouse up event on page.
219        /// </summary>
220        /// <param name="button">Mouse button to simulate.</param>
221        public void MouseUp(MouseButton button)
222        {
223            MouseUpAsync(button).Wait();
224            
225        }
226
227        private async Task MouseUpAsync(MouseButton button)
228        {
229            await m_page.Mouse.UpAsync(new ClickOptions { Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });
230        }
231
232        /// <summary>
233        /// Simulates a mouse down event on page.
234        /// </summary>
235        /// <param name="button">Mouse button to simulate.</param>
236        public void MouseDown(MouseButton button)
237        {
238            MouseDownAsync(button).Wait();
239        }
240
241        private async Task MouseDownAsync(MouseButton button)
242        {
243            await m_page.Mouse.DownAsync(new ClickOptions { Button = button == MouseButton.Left ? PuppeteerSharp.Input.MouseButton.Left : PuppeteerSharp.Input.MouseButton.Right });
244
245        }
246
247        /// <summary>
248        /// Simulates a touch tap on a page.
249        /// </summary>
250        /// <param name="target">Javascript selector for element to tap on.</param>
251        public void TapScreen(string target)
252        {
253            TapScreenAsync(target).Wait();
254        }
255
256        private async Task TapScreenAsync(string target)
257        {
258            await m_page.TapAsync(target);
259        }
260
261        /// <summary>
262        /// Generates a pdf of the page.
263        /// </summary>
264        /// <returns>Stream containing the pdf data.</returns>
265        public Stream CreatePdf()
266        {
267            var data = CreatePdfAsync();
268            data.Wait();
269            return data.Result;
270
271        }
272
273        private async Task<Stream> CreatePdfAsync()
274        {
275            return await m_page.PdfStreamAsync();
276        }
277
278        /// <summary>
279        /// Waits for expression to be to be true.
280        /// </summary>
281        /// <param name="expression">Expression to wait on.</param>
282        public void WaitOnScript(string expression)
283        {
284            WaitOnScriptAsync(expression).Wait();
285        }
286
287        private async Task WaitOnScriptAsync(string expression)
288        {
289            await m_page.WaitForExpressionAsync(expression);
290        }
291
292        /// <summary>
293        /// Selects element on page to have focus.
294        /// </summary>
295        /// <param name="target">Javascript selector to make have focus.</param>
296        public void Focus(string target)
297        {
298            FocusAsync(target).Wait();
299        }
300
301        private async Task FocusAsync(string target)
302        {
303            await m_page.FocusAsync(target);
304        }
305
306        /// <summary>
307        /// Clicks on target element on page.
308        /// </summary>
309        /// <param name="target">Javascript selector of element to click on.</param>
310        public void Click(string target)
311        {
312            ClickAsync(target).Wait();
313        }
314
315        private async Task ClickAsync(string target)
316        {
317            await m_page.ClickAsync(target);
318        }
319
320        /// <summary>
321        /// Html content of page. Useful for scraping the html directly.
322        /// </summary>
323        public string Content
324        {
325            get
326            {
327                var data = m_page.GetContentAsync();
328                data.Wait();
329                return data.Result;
330            }
331            set
332            {
333                var data = m_page.SetContentAsync(value);
334                data.Wait();
335            }
336        }
337
338        /// <inheritdoc />
339        /// <summary>
340        /// Dispose method.
341        /// This will close out chromium session.
342        /// </summary>
343        public void Dispose()
344        {
345            m_browser?.Dispose();
346            m_page?.Dispose();
347        }
348    }
349}
350
Full Screen

Program.cs

Source: Program.cs Github

copy
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Linq;
5using System.Text;
6using System.Threading.Tasks;
7using PuppeteerSharp;
8using PuppeteerSharp.Input;
9
10namespace TryingPuppeeteerSharp
11{
12    class Program
13    {
14        static async Task Main(string[] args)
15        {
16            await Run();
17
18            Process.Start("dwarf.jpg");
19            Console.WriteLine("Dwarf");
20        }
21
22        static async Task Run()
23        {
24            string url = "https://www.transformice.com/";
25            var browser = await Puppeteer.LaunchAsync(new LaunchOptions
26            {
27                Headless = false
28            });
29            var page = await browser.NewPageAsync();
30
31            await page.SetViewportAsync(new ViewPortOptions
32            {
33                Width = 1800,
34                Height = 1080
35            });
36
37            await page.GoToAsync(url);
38
39            await page.ScreenshotAsync("dwarf.jpg");
40        }
41    }
42}
43
Full Screen

MakeTweet.cs

Source: MakeTweet.cs Github

copy
1using PuppeteerSharp;
2using PuppeteerSharp.Input;
3using System;
4using System.Collections.Generic;
5using System.IO;
6using System.Text;
7using System.Threading.Tasks;
8
9namespace Flight_tracker
10{
11    class MakeTweet
12    {
13        static Browser browser;
14        static Page page;
15        static async Task launchBrowser()
16        {
17            LaunchOptions ops = new LaunchOptions();
18            ops.UserDataDir = Directory.GetCurrentDirectory() + "\\cache";
19            ops.Headless = true;
20            new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
21            browser = await Puppeteer.LaunchAsync(ops);
22
23            page = (await browser.PagesAsync())[0];
24
25            page.DefaultTimeout = 0;
26            var navigation = new NavigationOptions
27            {
28                Timeout = 0,
29                WaitUntil = new[] {
30                        WaitUntilNavigation.Networkidle2 }
31            };
32            ViewPortOptions v = new ViewPortOptions();
33            v.Width = 1920;
34            v.Height = 1000;
35            await page.SetViewportAsync(v);
36            await page.GoToAsync("https://twitter.com/", navigation);
37        }
38        static async Task Main(string[] args)
39        {
40            await launchBrowser();
41            await makeTweetAsync("Hello, I am currently still working on the automation of this account updates on Putin's jet will start soon!");
42        }
43        public static async Task makeTweetAsync(String str)
44        {
45            await page.SetCacheEnabledAsync(true);
46            await page.SetJavaScriptEnabledAsync(true);
47            await page.ClickAsync("a[data-testid='SideNav_NewTweet_Button']");
48            await page.ClickAsync("div[data-testid='tweetTextarea_0']");
49            TypeOptions op = new TypeOptions();
50            op.Delay = 10;
51            await page.TypeAsync("div[data-testid='tweetTextarea_0']", str,op);
52            await page.ClickAsync("div[data-testid='tweetButton']");
53            await page.WaitForNavigationAsync();
54            //await browser.CloseAsync();
55        }
56    }
57}
58
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTestÔÇÖs cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Most used method in Page

Trigger SetViewportAsync code on LambdaTest Cloud Grid

Execute automation tests with SetViewportAsync on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)