Search code examples
pythonyoutubeurllibpython-re

How to get full name of the YouTube video after search a video using python?


import urllib.request
import re
search_keyword ="music"
search_song_url = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search_keyword)
video_ids = re.findall(r"watch\?v=(\S{11})", search_song_url.read().decode())
url="https://www.youtube.com/watch?v=" + video_ids[0]
str(url)
print(url)

From this code, I get the proper URL of youtube video but I want the full name of the video. I had tried so much but I unable to find the full name of the video.

Please help me to get the full name of the video.


Solution

  • You can use get the html of the url you just got. Then use lxml to make it a lot easier.

    import urllib.request
    import re
    import lxml
    from lxml import etree
    
    search_keyword ="music"
    search_song_url = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + search_keyword)
    video_ids = re.findall(r"watch\?v=(\S{11})", search_song_url.read().decode())
    url = str("https://www.youtube.com/watch?v=" + video_ids[0])
    
    youtube = etree.HTML(urllib.request.urlopen(url).read())
    video_title = youtube.xpath("/html/head/title")
    print (video_title[0].text)
    

    Works perfectly for me.