I am trying to play a video via YouTube using puppeteer using C#
Here’s my code so far:
If you can provide me with or guide me correct way appreciate it a lot:
using System;
using System.Threading.Tasks;
using PuppeteerSharp;
namespace SOYoutube
{
class Program
{
static async Task Main(string[] args)
{
// Define the URL of the question
string questionUrl = "www.youtube.com";
// Download the Chromium revision if not already done
var browserFetcher = new BrowserFetcher();
await browserFetcher.DownloadAsync();
// Launch a new browser instance
await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions
{
Headless = false // Set to true if you want to run in headless mode
});
// Open a new page
await using var page = await browser.NewPageAsync();
// Navigate to the question page
await page.GoToAsync(questionUrl);
// Wait for the upvote button to be present in the DOM
await page.WaitForSelectorAsync("");
// Click the upvote button
await page.ClickAsync("");
// Keep the browser open for a while to observe the action
await Task.Delay(5000);
// Close the browser
await browser.CloseAsync();
}
}
}
Page only open only not playing any video
New contributor
user13821471 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
Before you play the video you need to wait until the network is idle and DOM content is loaded to the page. Then you can click on play. Refer to the code for more reference:
using PuppeteerSharp;
using System;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
await PlayYouTubeVideo();
}
static async Task PlayYouTubeVideo()
{
var launchOptions = new LaunchOptions
{
Headless = false
};
using (var browser = await Puppeteer.LaunchAsync(launchOptions))
using (var page = await browser.NewPageAsync())
{
try
{
await page.GoToAsync("https://www.youtube.com/watch?v=cYYdmLkRKRQ", waitUntil: new[] { WaitUntilNavigation.Networkidle2 }); // Give your URL here
await page.WaitForSelectorAsync(".html5-video-container", new WaitForSelectorOptions { Timeout = 5000 });
var playButton = await page.QuerySelectorAsync(".ytp-play-button");
await playButton.ClickAsync();
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
}
}