1

I want to create a python program that allows me to input search terms and return the url of the first result

def search(search):
    #Gets the youtube url of the first result
    return url

Something along those lines. I don't know too much about youtube-dl nor how to implement it into python as I couldn't find much info on how to do this through google.

Lucas Kumara
  • 19
  • 2
  • 5

2 Answers2

1

If you are using python 3.5 then this is pretty simple. I don't know if this works in previous versions of python 3.x. The result that is returned here is a list of the URLs. So if you want the first result use search(text)[0]

import subprocess 
def search(text):
    command=['youtube-dl', 'ytsearch:"' + text+'"', '-g']
    result=subprocess.run(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE,universal_newlines=True).stdout.split()
    return result
Gnik
  • 204
  • 3
  • 10
0

You must know that every good linux programs has some instructions built-in. To see them, try youtube-dl --help or man youtube-dl

For your question, from the command line:

youtube-dl "ytsearch:Rick Astley" -g

No idea about python, but it should be pretty close to the following equivalent in bash.

#!/bin/bash
youtube-dl "ytsearch: $1" -g

just save this in a file, give it the «execution permision» «allow file to be executed as program» or from the command line chmod +x myprogram.

Then to call:

./myprogram 'rick astley'

This will output the first link. The procedure is exactly the same in many languages: python, php, bash (etc). This is a bash script.

Good luck ;)

NVRM
  • 11,480
  • 1
  • 88
  • 87