5

I try this and don't know how to open the first video. This code opens the search in the browser.

import webbrowser

def findYT(search):
    words = search.split()

    link = "http://www.youtube.com/results?search_query="

    for i in words:
        link += i + "+"

    time.sleep(1)
    webbrowser.open_new(link[:-1])

This successfully searches the video, but how do I open the first result?

Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34

2 Answers2

4

The most common approach would be to use two very popular libraries: requests and BeautifulSoup. requests to get the page, and BeautifulSoup to parse it.

import requests
from bs4 import BeautifulSoup

import webbrowser

def findYT(search):
    words = search.split()

    search_link = "http://www.youtube.com/results?search_query=" + '+'.join(words)
    search_result = requests.get(search_link).text
    soup = BeautifulSoup(search_result, 'html.parser')
    videos = soup.select(".yt-uix-tile-link")
    if not videos:
        raise KeyError("No video found")
    link = "https://www.youtube.com" + videos[0]["href"]

    webbrowser.open_new(link)

Note that it is recommended not to use uppercases in python while naming variables.

Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
Hurried-Helpful
  • 1,850
  • 5
  • 15
1

To do that you have to webscrape. Python can´t see what is on your screen. You have to webscrape the youtube page you are searching and then you can open the first <a> that comes up for example. ('' is a url tag in html)

Things you need for that:

  • BeautifulSoup or selenium for example
  • requests

That should be all that you need to do what you want.

Joshua Varghese
  • 5,082
  • 1
  • 13
  • 34
Whoozy
  • 161
  • 17