Search code examples
c#youtubevideo-streamingsearchbar

How to use string var to search website/ go to website


I am learning c# currently and I have questions about how to control website in c#, how c# can work with websites.

For example, let's say that I opened a chrome with a blank page.

Process.Start("http://blank.org/"); //<-  like this. 

(Is there any way that I can open a blank page? - not very important tho..)

Question 1)

Now I would like to go to YouTube, using the address bar. For example, I have :

string address = "www.youtube.com"

and I want to input this string in the address bar and automatically click search button. Is it possible?

Question 2)

Let's say that I solved the question 1. After that, I would like to search for something, using the search bar For example, I have :

string keyword = "funny cat video";

Then I would like to input this keyword on the search bar and then search for it.

How can I make this? Is it possible in c#?

Question 3)

And then I want to play the first result on the screen. For example, like this : The first result that is found with the keyword

In this case, what should I do?

Thank you so much in advance. I have been googling all day and I couldn't find how to do.


Solution

  • Try this for a simple search:

    string youtubeUrl = @"https://www.youtube.com";
    string keyword = "funny cat video";
    
    string searchUrl = string.Format("{0}/results?search_query={1}", youtubeUrl, keyword.Replace(" ", "+"));
    Process.Start(searchUrl); 
    

    If you want to manipulate the search results, then you can use the YouTube API to obtain the first result youtube VideoId.

    If you don't want to use the YouTube Search API, then you will need to download the html and parse it to find the first video link on the page ( like in jquery: $("a[href^='/watch?v=']") ).

    Once you have the youtube video id you want you can open and watch it.

    string youtubeUrl = @"https://www.youtube.com";
    string youtubeVideoId = "njSyHmcEdkw"; 
    
    string watchVideoUrl = string.Format("{0}/watch?v={1}", youtubeUrl, youtubeVideoId);
    
    Process.Start(watchVideoUrl);