Home » Kodi » Python – How to Create Kodi Video Addon – Youtube Search

Python – How to Create Kodi Video Addon – Youtube Search

Python – How to Create Kodi Video Addon – Youtube Search

We are almost there peeps. This tutorial will result in a working Kodi video addon. The addon will take user input, search youtube, and then list and play the videos. Excited? So are we. Let’s go ahead and see how to create Kodi video addon – Youtube search.

Create Youtube Search Kodi Video Addon

Python – How to Create Kodi Video Addon – Youtube Search

Disclaimer

This article is for Educational Purposes only. Please check the laws for web scraping for your country and the website you are scraping. We are not responsible for companies suing you or law enforcement, intelligence or secret services knocking at your door.

Pre-Requisites

Make sure you have gone through all the tutorials listed on below link.

Create Kodi Video Addon – Kodi Addon Development

We will be using code from almost all tutorials linked on the article.

Also install the Youtube Kodi addon from the official Kodi team. Kodi Home screen -> Addons -> Addon Manager -> Install from Repository -> Kodi Repository -> Video Addons -> Youtube.

Purpose

The purpose of this addon or plugin is to

  1. Search Youtube for a term entered by the user
  2. display the search results
  3. Play the Video user selects

Addon name – plugin.video.utub3scrap3

The code for this addon can be found here, and you can grab the addon zip from here.

Python – How to Create Kodi Video Addon – Youtube Search

Let’s Dive Into the Code

addon.xml

We need to add dependencies of below modules for our addon to work.

<import addon="script.module.urlresolver" version="3.0.0"/> 

<import addon="script.module.requests"    version="2.12.4"/> 

<import addon="script.module.beautifulsoup4" version="4.3.2"/>

 

All the code for this addon is present in the file youtube_addon.py. Almost all of the code is covered in the link in pre-requisites section.

Lines 1 – 10

import sys
import xbmc
import xbmcgui
import xbmcaddon
import xbmcplugin
import urllib
import urlparse
import urlresolver
import requests
from bs4 import BeautifulSoup

Here we are importing all the modules we need for our addon.

Lines 13 – 15

base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])

These lines are the basics for any Kodi addon. A detailed explanation can be found at below link.

Sys.argv explained, Building a menu

Line 17 – 20

# set url to be scraped
scrape_url = "https://www.youtube.com"
search_url = "/results?search_query="
mozhdr = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'}

Here we are setting the url to be scraped, and a header. A detailed explanation can be found at below link.

Video Scraping with Python and BeautifulSoup

Lines 23 – 24

def build_url(query):
 return base_url + '?' + urllib.urlencode(query)

We are creating a function to encode our menus as url’s. A detailed explanation can be found at below link.

Sys.argv explained, Building a menu

Lines 27 – 37

def getusersearch(website):
 kb = xbmc.Keyboard('default', 'heading')
 kb.setDefault('Enter Search Word')
 kb.setHeading(website + 'Search')
 kb.setHiddenInput(False)
 kb.doModal()
 if (kb.isConfirmed()):
 search_term = kb.getText()
 return(search_term)
 else:
 return

We create a function to get user input. A detailed explanation can be found at below link.

How to Take User Input in Kodi Using Python

Lines 40 – 45

Here we crate two functions for our menus.

def addMenuitem(url, li, folder):
 return xbmcplugin.addDirectoryItem(handle=addon_handle, url=url, listitem=li, isFolder=folder)

The first function addMenuitem takes three parameters as input

url – address of the video to be played

li – list item for the menu

folder – determines whether the item to be added to the menu is a folder or a playable item.

If an item is added successfully to the menu, it returns True else False.

def endMenu():
 xbmcplugin.endOfDirectory(addon_handle)

The function endMenu does what the name suggests, it tells Kodi that we have no more items to be added to the menu.

A detailed explanation of addDirectoryItem and endOfDirectory can be found at below link.

How to Play a Video in Kodi

Lines 48 – 60

def bstheurl(url):
 sb_get = requests.get(url, headers=mozhdr)
 soupeddata = BeautifulSoup(sb_get.content, "html.parser")
 yt_links = soupeddata.find_all("a", class_="yt-uix-tile-link")
 for x in yt_links:
 yt_href = x.get("href")
 yt_title = x.get("title")
 yt_final = scrape_url + yt_href
 url = build_url({'mode': 'play', 'playlink': yt_final})
 li = xbmcgui.ListItem(yt_title, iconImage='DefaultVideo.png')
 li.setProperty('IsPlayable', 'true')
 addMenuitem(url, li, False)
 endMenu()

Most of the code in this function is from out tutorial on Video Scraping. Click the link below for more details.

Video Scraping with Python and BeautifulSoup

Below are the lines we have added to function.

url = build_url({'mode': 'play', 'playlink': yt_final})
 li = xbmcgui.ListItem(yt_title, iconImage='DefaultVideo.png')
 li.setProperty('IsPlayable', 'true')
 addMenuitem(url, li, False)
 endMenu()

These lines create a menu item for each Youtube video found, and the last line (endmenu()) just ends the menu.

Lines 63 – 89

def resolve_url(url):
 duration = 7500 # in milliseconds
 message = "Cannot Play URL"
 stream_url = urlresolver.HostedMediaFile(url=url).resolve()
 # If urlresolver returns false then the video url was not resolved.
 if not stream_url:
 dialog = xbmcgui.Dialog()
 dialog.notification("URL Resolver Error", message,
 xbmcgui.NOTIFICATION_INFO, duration)
 return False
 else:
 return stream_url



def play_video(path):
 """
 Play a video by the provided path.
 :param path: str
 """
 # Create a playable item with a path to play.
 play_item = xbmcgui.ListItem(path=path)
 vid_url = play_item.getfilename()
 stream_url = resolve_url(vid_url)
 if stream_url:
 play_item.setPath(stream_url)
 # Pass the item to the Kodi player.
 xbmcplugin.setResolvedUrl(addon_handle, True, listitem=play_item)

Both these functions are from our tutorial on how to play a video using URL Resolver. Hit the link below for a detailed explanation.

How to Play Video Using URL Resolver in Kodi Using Python

 

Lines 94 – 98

if mode is None:
 url = build_url({'mode': 'search', 'site': 'youtube'})
 li = xbmcgui.ListItem('Youtube Search', iconImage='DefaultFolder.png')
 addMenuitem(url, li, True)
 endMenu()

This is where we create a menu item called Youtube Search when addon is first opened.

Youtube Search Addon - main menu

Lines 100 – 106

elif mode[0] == 'search':
 website = args['site'][0]
 search_string = getusersearch(website)
 yotube_search_url = scrape_url + search_url + \
 search_string.replace(" ", "+")
 xbmcplugin.setContent(addon_handle, 'movies')
 bstheurl(yotube_search_url)

This is the piece of code executed when user selects Youtube Search.

Youtube Search Addon-search

search_string = getusersearch(website)

The function getusersearch is called which takes user input.

yotube_search_url = scrape_url + search_url + \
 search_string.replace(" ", "+")

Here we are assigning the variable yotube_search_url to scrape_url + search_url + whatever term user entered for search. As we know spaces are replaced by + sign when you search a string with spaces on youtube, we are doing the same by replacing spaces with a + sign. The \ is just a continuation in Python.

Youtube Search Addon-seach string

So, let’s say user entered Game of Thrones as search word.

search_string.replace(" ","+")

will make it Game+of+Thrones.

and yotube_search_url as https://www.youtube.com/results?search_query=game+of+thrones

 bstheurl(yotube_search_url)

We are passing the complete url to function bstheurl, which will

  1. request url for us from youtube
  2. get video link and title using Beautiful Soup
  3. add those titles and links to a menu

Youtube Search Addon-results

Lines 108 – 100

elif mode[0] == 'play':
 final_link = args['playlink'][0]
 play_video(final_link)

This is the piece of code which is executed when user selects a video.

Python – How to Create Kodi Video Addon – Youtube Search

Bugs

A bug in the code is that if search term is the name of Youtube Channel, that is also displayed in the results.

Limitations

The code only processes page 1 of search results.

 

Do you STREAM on Kodi WITHOUT a VPN?

We STRONGLY suggest you use a VPN Service like IPVanish.

Why VPN? 1. Stay Secure and Anonymous Online 2. Stream Content Anonymously 3. Access Geo Locked Content 4. Hide Your Activity from your ISP

Why IPVanish? 1. They Keep No Logs = No Tracking 2. Native apps for Android, Android TV, iOS, Mac, Linux 3. No Speed Slowdown 4. Highly Recommended 5. 7 Days Money Back Guarantee

Sign-Up for IPVanish