Search code examples
pythonpython-3.xweburlpytube

Getting KeyError: 'url' with PyTube


I get the error sometimes when downloading a video. For example, I can attempt to download the video and it will download, the next time I run the script that video will not download and the error will be thrown.

def search_youtube(song,randomString,playlist_name):
 results = YoutubeSearch(song, max_results=1).to_dict()
 for v in results:
    url = 'https://www.youtube.com' + v['link']
    print(url)

    _filename = song
    format_input = 'mp4'
    format_output = 'mp3'

    print("Downloading...." + ' ' + song)
    time.sleep(5)
    YouTube(url).streams.first().download(filename=randomString,output_path=playlist_name)

Solution

  • I have just fixed this issue. Follow these steps.

    1. Go to pytube directory in site-packages. If you're not sure where full location is use: pip show pytube3. You'll see location of site-packages.
    2. In site-packages/pytube folder opened from above location, you'll see a file called extract.py. Open that file in your IDE or text-editor.
    3. You'll see a function called apply_descrambler . Inside that function, in line 301 probably, you'll see something like parse_qs(formats[i]["cipher"]) for i, data in enumerate(formats)
    4. Replace cipher in formats[i]["cipher"] with signatureCipher . Thus that line becomes, parse_qs(formats[i]["signatureCipher"]) for i, data in enumerate(formats)
    5. pytube3 should work fine now.