Git Product home page Git Product logo

pafy's Introduction

image

image

image

Code Health

image

Wheel Status

Features

  • Retreive metadata such as viewcount, duration, rating, author, thumbnail, keywords
  • Download video or audio at requested resolution / bitrate / format / filesize
  • Command line tool (ytdl) for downloading directly from the command line
  • Retrieve the URL to stream the video in a player such as vlc or mplayer
  • Works with age-restricted videos and non-embeddable videos
  • Small, standalone, single importable module file (pafy.py)
  • Select highest quality stream for download or streaming
  • Download video only (no audio) in m4v or webm format
  • Download audio only (no video) in ogg or m4a format
  • Retreive playlists and playlist metadata
  • Works with Python 2.6+ and 3.3+
  • Optionally depends on youtube-dl (recommended; more stable)

Documentation

Full documentation is available at http://pythonhosted.org/pafy

Usage Examples

Here is how to use the module in your own python code. For command line tool (ytdl) instructions, see further below

>>> import pafy

create a video instance from a YouTube url:

>>> url = "https://www.youtube.com/watch?v=bMt47wvK6u0"
>>> video = pafy.new(url)

get certain attributes:

>>> video.title
'Richard Jones: Introduction to game programming - PyCon 2014'

>>> video.rating
5.0

>>> video.viewcount, video.author, video.length
(1916, 'PyCon 2014', 10394)

>>> video.duration, video.likes, video.dislikes
('02:53:14', 25, 0)

>>> print(video.description)
Speaker: Richard Jones

This tutorial will walk the attendees through development of a simple game using PyGame with time left over for some experimentation and exploration of different types of games.

Slides can be found at: https://speakerdeck.com/pycon2014 and https://github.com/PyCon/2014-slides

list available streams for a video:

>>> streams = video.streams
>>> for s in streams:
...     print(s)
...
normal:mp4@1280x720
normal:webm@640x360
normal:mp4@640x360
normal:flv@320x240
normal:3gp@320x240
normal:3gp@176x144

show all formats, file-sizes and their download url:

>>> for s in streams:
...    print(s.resolution, s.extension, s.get_filesize(), s.url)
...
1280x720 mp4 2421958510 https://r1---sn-aiglln7e.googlevideo.com/videoplayba[...]
640x360 webm 547015732 https://r1---sn-aiglln7e.googlevideo.com/videoplaybac[...]
640x360 mp4 470655850 https://r1---sn-aiglln7e.googlevideo.com/videoplayback[...]
320x240 flv 345455674 https://r1---sn-aiglln7e.googlevideo.com/videoplayback[...]
320x240 3gp 208603447 https://r1---sn-aiglln7e.googlevideo.com/videoplayback[...]
176x144 3gp 60905732 https://r1---sn-aiglln7e.googlevideo.com/videoplayback?[...]

get best resolution regardless of file format:

>>> best = video.getbest()
>>> best.resolution, best.extension
('1280x720', 'mp4')

get best resolution for a particular file format: (mp4, webm, flv or 3gp)

>>> best = video.getbest(preftype="webm")
>>> best.resolution, best.extension
('640x360', 'webm')

get url, for download or streaming in mplayer / vlc etc:

>>> best.url
'http://r12---sn-aig7kner.c.youtube.com/videoplayback?expire=1369...

Download video and show progress:

>>> best.download(quiet=False)
3,734,976 Bytes [0.20%] received. Rate: [ 719 KB/s].  ETA: [3284 secs]

Download video, use specific directory and/or filename:

>>> filename = best.download(filepath="/tmp/")

>>> filename = best.download(filepath="/tmp/Game." + best.extension)

Get audio-only streams (m4a and/or ogg vorbis):

>>> audiostreams = video.audiostreams
>>> for a in audiostreams:
...     print(a.bitrate, a.extension, a.get_filesize())
...
256k m4a 331379079
192k ogg 172524223
128k m4a 166863001
128k ogg 108981120
48k m4a 62700449

Download the 2nd audio stream from the above list:

>>> audiostreams[1].download()

Get the best quality audio stream:

>>> bestaudio = video.getbestaudio()
>>> bestaudio.bitrate
'256'

Download the best quality audio file:

>>> bestaudio.download()

show all media types for a video (video+audio, video-only and audio-only):

>>> allstreams = video.allstreams
>>> for s in allstreams:
...     print(s.mediatype, s.extension, s.quality)
...

normal mp4 1280x720
normal webm 640x360
normal mp4 640x360
normal flv 320x240
normal 3gp 320x240
normal 3gp 176x144
video m4v 1280x720
video webm 1280x720
video m4v 854x480
video webm 854x480
video m4v 640x360
video webm 640x360
video m4v 426x240
video webm 426x240
video m4v 256x144
video webm 256x144
audio m4a 256k
audio ogg 192k
audio m4a 128k
audio ogg 128k
audio m4a 48k

Installation

pafy can be installed using pip:

$ [sudo] pip install pafy

or use a virtualenv if you don't want to install it system-wide:

$ virtualenv venv
$ source venv/bin/activate
$ pip install pafy

Command Line Tool (ytdl) Usage

usage: ytdl [-h] [-i] [-s]
            [-t {audio,video,normal,all} [{audio,video,normal,all} ...]]
            [-n N] [-b] [-a]
            url

YouTube Download Tool

positional arguments:
  url                   YouTube video URL to download

optional arguments:
  -h, --help            show this help message and exit
  -i                    Display vid info
  -s                    Display available streams
  -t {audio,video,normal,all} [{audio,video,normal,all} ...]
                        Stream types to display
  -n N                  Specify stream to download by stream number (use -s to
                        list available streams)
  -b                    Download the best quality video (ignores -n)
  -a                    Download the best quality audio (ignores -n)

ytdl Examples

Download best available resolution (-b):

$ ytdl -b "http://www.youtube.com/watch?v=cyMHZVT91Dw"

Download best available audio stream (-a) (note; the full url is not required, just the video id will suffice):

$ ytdl -a cyMHZVT91Dw

get video info (-i):

$ ytdl -i cyMHZVT91Dw

list available dowload streams:

$ ytdl cyMHZVT91Dw

Stream Type    Format Quality         Size            
------ ----    ------ -------         ----            
1      normal  webm   [640x360]       33 MB
2      normal  mp4    [640x360]       23 MB
3      normal  flv    [320x240]       14 MB
4      normal  3gp    [320x240]        9 MB
5      normal  3gp    [176x144]        3 MB
6      audio   m4a    [48k]            2 MB
7      audio   m4a    [128k]           5 MB
8      audio   ogg    [128k]           5 MB
9      audio   ogg    [192k]           7 MB
10     audio   m4a    [256k]          10 MB

Download mp4 640x360 (ie. stream number 2):

$ ytdl -n2 cyMHZVT91Dw

Download m4a audio stream at 256k bitrate:

$ ytdl -n10 cyMHZVT91Dw

IRC

The mps-youtube irc channel (#mps-youtube on Freenode) can be used for discussion of pafy.

pafy's People

Contributors

davidfischer-ch avatar divyansh2512 avatar dokime7 avatar ekisu avatar hugovk avatar ids1024 avatar inspectorg4dget avatar kewitz avatar kiorky avatar kkrolczyk avatar kraetzin avatar krishnawhite avatar kyrias avatar lol768 avatar noembryo avatar np1 avatar phosphorus-m avatar pulpe avatar regisb avatar ritiek avatar ryin1 avatar sadolit avatar stav avatar stefanjenkner avatar tommysolsen avatar trygveaa avatar vn-ki avatar williamroot avatar zetasyanthis avatar zgrimshell avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pafy's Issues

fetching categoryId using Pafy

Dear creator of pafy,
cold you please add a attribute to fetch categoryId?

I am successfully able to see title and description using
video=pafy.new("videoID")
video.title
video.description
video.categoryId #seeking this ferature

if possible please add
thank you

video CMbpFlLVjcQ, name with ':'

can't download CMbpFlLVjcQ although I write an explicit file name
same like issue 38

pafy.new('CMbpFlLVjcQ').getbestaudio(preftype="m4a").download(quiet = True, filepath='Akala - Dead Prez.m4a')

Traceback (most recent call last):
File "<pyshell#4>", line 1, in
pafy.new('CMbpFlLVjcQ').getbestaudio(preftype="m4a").download(quiet = True, filepath='Akala - Dead Prez.m4a')
File "build\bdist.win32\egg\pafy\pafy.py", line 769, in download
os.rename(tempfname, fname)
WindowsError: [Error 87]

I try to add print Version

Too many versions but I want to know which version is used ...

And try put this but dont work :

def main():
    """ Parse args and show info or download. """
    # pylint: disable=R0912
    # too many branches
    description = "YouTube Download Tool"
    parser = argparse.ArgumentParser(description=description)
    paa = parser.add_argument
    paa('-v', '--verbose', help="Print version and exit",
        action="store_true")
    paa('url', help="YouTube video URL to download")
    paa('-i', required=False, help="Display vid info", action="store_true")
    paa('-s', help="Display available streams", action="store_true")
    paa('-t', help="Stream types to display", type=str, nargs="+",
        choices="audio video normal all".split())
    paa('-n', required=False, metavar="N", type=int, help='Specify stream to '
        'download by stream number (use -s to list available streams)')
    paa('-b', required=False, help='Download the best quality video (ignores '
        '-n)', action="store_true")
    paa('-a', required=False, help='Download the best quality audio (ignores '
        '-n)', action="store_true")

    args = parser.parse_args()
    vid = pafy.new(args.url)
    streams = []

    if args.verbose:
        print (__version__)

and the result is this :
ytdl --verbose
usage: ytdl [-h] [-v] [-i] [-s]
[-t {audio,video,normal,all} [{audio,video,normal,all} ...]]
[-n N] [-b] [-a]
url
ytdl: error: too few arguments

or : ytdl --help
usage: ytdl [-h] [-v] [-i] [-s]
[-t {audio,video,normal,all} [{audio,video,normal,all} ...]]
[-n N] [-b] [-a]
url

YouTube Download Tool

positional arguments:
url YouTube video URL to download

optional arguments:
-h, --help show this help message and exit
-v, --verbose Print version and exit
-i Display vid info
-s Display available streams
-t {audio,video,normal,all} [{audio,video,normal,all} ...]
Stream types to display
-n N Specify stream to download by stream number (use -s to
list available streams)
-b Download the best quality video (ignores -n)
-a Download the best quality audio (ignores -n)

error while downloading some of video

alok@alok-ThinkPad-L430:~/$ ytdl -s https://www.youtube.com/watch?v=V8QgHP3NEFI
Traceback (most recent call last):
File "/usr/local/bin/ytdl", line 170, in
main()
File "/usr/local/bin/ytdl", line 112, in main
vid = pafy.new(args.url)
File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 131, in new
return Pafy(url, basic, gdata, signature, size, callback)
File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 925, in init
self.fetch_basic()
File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 986, in fetch_basic
self._process_streams()
File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 1023, in _process_streams
adpt_streams = [Stream(z, self) for z in self.asm]
File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 607, in init
self._resolution = g.itags[self.itag][0]
KeyError: u'278'

why I am getting this error for some of videos ?

video - pIp9Qi6MnGI

pafy 0.3.52
python 2.7

pafy.new('pIp9Qi6MnGI')

Traceback (most recent call last):
File "<pyshell#7>", line 1, in
pafy.new('pIp9Qi6MnGI')
File "build\bdist.win32\egg\pafy\pafy.py", line 129, in new
return Pafy(url, basic, gdata, signature, size, callback)
File "build\bdist.win32\egg\pafy\pafy.py", line 824, in init
self.fetch_basic()
File "build\bdist.win32\egg\pafy\pafy.py", line 883, in fetch_basic
self._process_streams()
File "build\bdist.win32\egg\pafy\pafy.py", line 919, in _process_streams
streams = [Stream(z, self) for z in self.sm]
File "build\bdist.win32\egg\pafy\pafy.py", line 540, in init
self._rawurl = sm['url']
KeyError: u'url'

Thanks

I finally succeeded to download a 3,000 song list, with (almost) no errors :)
Thanks

[Question] .mp3 extension ?

Hello,

I'm using this api, and I would like to know if it is posssible to have an ".mp3" extension with getbestaudio() function.

Thanks

IOError [Errno 2] when trying to download video to specific filepath

I'm trying to download a video to a specific folder using the code below -

def dlVideo(url):
    video = pafy.new(url)
    best = video.getbest()
    dlPath = "/vid/" + best.title + "." + best.extension
    best.download(quiet=False, filepath=dlPath)

It shows me this when I run it -

File "dl.py", line 37, in dlVideo
    best.download(quiet=False, filepath=dlPath)
File "/Users/achalv/Desktop/Projects/pafy/pafy.py", line 746, in download
    outfh = open(temp_filepath, fmode)
IOError: [Errno 2] No such file or directory: u'/vid/Funny Cricket Wonders and Blunders, (Part 10 , Run Outs).mp4.temp'

Works perfectly as long as I don't specify a custom filepath for the download.

Trying to figure out what's wrong, and if it's an issue on my end.
Thanks!

IOError: no match for a=fo.XG(a,15)

Hi,
sometimes i get a error, try to run the next line and see if you get an error after some time:

while(True): print '.',; name = pafy.new('O5nWH10R_uI').getbestaudio().title

(pafy 0.3.54)

Traceback (most recent call last):
File "<pyshell#5>", line 1, in
while(True): print '.',; name = pafy.new('O5nWH10R_uI').getbestaudio().title
File "build\bdist.win32\egg\pafy\pafy.py", line 129, in new
return Pafy(url, basic, gdata, signature, size, callback)
File "build\bdist.win32\egg\pafy\pafy.py", line 841, in init
s[0].url # forces signature decryption
File "build\bdist.win32\egg\pafy\pafy.py", line 679, in url
sig = _decodesig(s, self._parent.js_url) if s else None
File "build\bdist.win32\egg\pafy\pafy.py", line 427, in _decodesig
solved = _solve(mainfunction, js_url)
File "build\bdist.win32\egg\pafy\pafy.py", line 376, in _solve
raise IOError("no match for %s" % part)
IOError: no match for a=fo.XG(a,15)

HTTPError: HTTP Error 410: Gone

Hi, please check:
pafy.new('K659Dh-VwVc').getbestaudio(preftype="m4a").download(quiet = True)

I get an error:

Traceback (most recent call last):
File "<pyshell#15>", line 1, in
pafy.new('K659Dh-VwVc').getbestaudio(preftype="m4a").download(quiet = True)
File "build\bdist.win32\egg\pafy\pafy.py", line 781, in download
response = g.opener.open(self.url)
File "C:\Python27\lib\urllib2.py", line 410, in open
response = meth(req, response)
File "C:\Python27\lib\urllib2.py", line 523, in http_response
'http', request, response, code, msg, hdrs)
File "C:\Python27\lib\urllib2.py", line 448, in error
return self._call_chain(_args)
File "C:\Python27\lib\urllib2.py", line 382, in _call_chain
result = func(_args)
File "C:\Python27\lib\urllib2.py", line 531, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 410: Gone

Fetching video caption(subtitle) list?

For some video there's a subtitle(s). e.g.

https://www.youtube.com/watch?v=McLq1hEq3UY

You can click CC button in the right-bottom corner in video player for captions. And there may be captions of different languages .

Technique details

  1. Get ytplayer.config.args.ttsurl from watchv page if it's present.
  2. Use "%s&type=list&tlangs=1&fmts=1&vssids=1&asrs=1" % ttsurl as url to fetch caption(subtitle) language list. (You can get language code list and caption format list)
  3. Use "%s&type=track&lang=en&name&kind=asr&fmt=1" % ttsurl as url to fetch real caption(subtitle) where lang, fmt key could be used to specify the language and format of the caption.

Difficulty

I find you've already fetched the watchv page in your get_js_sm function. So there will be a dilemma .

  1. If I do parsing ttsurl in get_js_sm function, I will not be able to get ttsurl anywhere other than in Stream class(I don't want to fetch subtitles in Stream class).
  2. If I write another function other than get_js_sm function, I need to fetch watchv page again and it's a waste of time.
    So ... any suggestions?

WindowsError 87 while download()

I tried this simple test.py code

import pafym

plurl = "http://www.youtube.com/playlist?list=PLBDA2E52FB1EF80C9"
playlist = pafym.get_playlist(plurl)

for n in range(0, 41):
    playlist['items'][n]['pafy'].getbest().download()

but pafy raised

Traceback (most recent call last):ived. Rate: [4078 KB/s].  ETA: [0 secs]
  File "test.py", line 11, in <module>
    playlist['items'][n]['pafy'].getbest().download()
  File "C:\Python27\lib\site-packages\pafy\pafy.py", line 769, in download
    os.rename(tempfname, fname)
WindowsError: [Error 87]

so I tried to change pafy.py line 731~738 (workaround)

from

        try:
            outfh = open(tempfname, fmode)

        except IOError:
            # remove special chars from filename
            fname = safe_filename(fname)
            tempfname = safename
            outfh = open(tempfname, fmode)

to

        #try:
        #    outfh = open(tempfname, fmode)

        #except IOError:
        #    # remove special chars from filename
        fname = safe_filename(fname)
        tempfname = safename
        outfh = open(tempfname, fmode)

and worked fine for me...

In my case, ':' caused the problem.
The temporary filepart name supposed to be

The Agricultural Revolution: Crash Course World History #1_Yocja_N5s1I_22.part

but it was

The Agricultural Revolution

then raised error.

Please download function check http://www.youtube.com/playlist?list=PLBDA2E52FB1EF80C9 by yourself. Thank you.

Some videos have no ogg audio stream

There seem to be some videos where no ogg stream is available:

>>> v = pafy.new('http://www.youtube.com/watch?v=cJEfixQv8Ho')
>>> v.getbestaudio()
audio:m4a@256k
>>> v.audiostreams
[audio:m4a@256k, audio:m4a@128k, audio:m4a@48k]

I'm not sure whether that's the fault of YouTube. If it is, I think a note in pafy's documentation that that is the case and why might make sense.

Provide channel slug

E.g., https://www.youtube.com/watch?v=cWd0hCqcqLg has "Shizzy VI" for author, but Shizzy's channel slug is "CallmeSixx".

The channel slug is usually static (I don't think it's possible to update it under normal circumstances) while the channel name can be updated at any point, making it unsuitable for archival purposes.

no match for jo.Dv

Hi,

It looks like another change of the signature for the copyright videos :(


Python 2.7.3 (default, Sep 26 2013, 16:35:25)
Type "copyright", "credits" or "license" for more information.

IPython 0.13.1.rc2 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.

In [1]: import pafy

In [2]: v=pafy.new('9bZkp7q19f0')
DEBUG:root:Fetched video info
DEBUG:root:Encrypted signature detected.
DEBUG:root:encoding: text/html; charset=utf-8
DEBUG:root:Fetched watchv page
DEBUG:root:Fetched javascript
DEBUG:root:Scanning js for main function.
DEBUG:root:Found main function: ko
DEBUG:root:Extracting function 'ko' from javascript
DEBUG:root:extracted function ko(a){a=a.split("");jo.Dv(a,28);jo.A5(a,69);jo.DO(a,1);jo.Dv(a,26);jo.Dv(a,40);jo.A5(a,57);jo.DO(a,1);return a.join("")};

DEBUG:root:scanning javascript for secondary functions.

IOError Traceback (most recent call last)
in ()
----> 1 v=pafy.new('9bZkp7q19f0')

/home/youtube/Pafy_v56/vinilla/pafy.py in new(url, basic, gdata, signature, size, callback)
127
128 """
--> 129 return Pafy(url, basic, gdata, signature, size, callback)
130
131

/home/youtube/Pafy_v56/vinilla/pafy.py in init(self, video_url, basic, gdata, signature, size, callback)
910
911 if self.ciphertag:
--> 912 s[0].url # forces signature decryption
913
914 if size:

/home/youtube/Pafy_v56/vinilla/pafy.py in url(self)
744
745 url, s = _get_matching_stream(enc_streams, self.itag)
--> 746 sig = _decodesig(s, self._parent.js_url) if s else None
747 self._url = _make_url(url, sig)
748

/home/youtube/Pafy_v56/vinilla/pafy.py in _decodesig(sig, js_url)
485 mainfunction['args'] = {param[0]: sig}
486 new.callback("Decrypting signature")
--> 487 solved = _solve(mainfunction, js_url)
488 dbg("Decrypted sig = %s...", solved[:30])
489 new.callback("Decrypted signature")

/home/youtube/Pafy_v56/vinilla/pafy.py in _solve(f, js_url)
420 break
421 else:
--> 422 raise IOError("no match for %s" % part)
423
424 if name == "split_or_join":

IOError: no match for jo.Dv(a,28)

AttributeError: 'NoneType' object has no attribute 'extension'

pafy.new('n_eU94M-DXM').getbestaudio().extension

gives me an error:

Traceback (most recent call last):
File "<pyshell#8>", line 1, in
pafy.new('n_eU94M-DXM').getbestaudio().extension
AttributeError: 'NoneType' object has no attribute 'extension'

video - IYFN_XwMCO8

pafy 0.3.64
python 2.7

pafy.new('IYFN_XwMCO8')

WARNING:root:ciphertag doesn't match signature type
WARNING:root:IYFN_XwMCO8
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 138, in new
    return Pafy(url, basic, gdata, signature, size, callback)
    File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 1041, in __init__
    self.fetch_basic()
    File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 1087, in fetch_basic
    self.dash = _extract_dash(self._dashurl)
    File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 274, in _extract_dash
    dashdata = fetch_decode(dashurl)
    File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 91, in fetch_decode
    req = g.opener.open(url)
    File "/usr/lib/python2.7/urllib2.py", line 407, in open
    response = meth(req, response)
    File "/usr/lib/python2.7/urllib2.py", line 520, in http_response
    'http', request, response, code, msg, hdrs)
    File "/usr/lib/python2.7/urllib2.py", line 445, in error
    return self._call_chain(*args)
    File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain
    result = func(*args)
    File "/usr/lib/python2.7/urllib2.py", line 528, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
    urllib2.HTTPError: HTTP Error 403: Forbidden

invalid characters bug

EDIT:

https://support.microsoft.com/kb/177506


test 1 :test
pafy.new('ffKj6jXDtAU').getbest().download()

Traceback (most recent call last):
File "<pyshell#15>", line 1, in
pafy.new('ffKj6jXDtAU').getbest().download()
File "build\bdist.win32\egg\pafy\pafy.py", line 769, in download
os.rename(tempfname, fname)
WindowsError: [Error 87]


test 2\test
pafy.new('WAz2lPPIy8E').getbest().download()

Traceback (most recent call last):
File "<pyshell#16>", line 1, in
pafy.new('WAz2lPPIy8E').getbest().download()
File "build\bdist.win32\egg\pafy\pafy.py", line 714, in download
raise IOError("Invalid directory: %s" % dirname)
IOError: Invalid directory: test 2


test 3*test
pafy.new('qSLDjJccvWI').getbest().download()

Traceback (most recent call last):
File "<pyshell#20>", line 1, in
pafy.new('qSLDjJccvWI').getbest().download()
File "build\bdist.win32\egg\pafy\pafy.py", line 769, in download
os.rename(tempfname, fname)
WindowsError: [Error 183]


test 4?test
pafy.new('I8wXrBWkEC8').getbest().download()

Traceback (most recent call last):
File "<pyshell#24>", line 1, in
pafy.new('I8wXrBWkEC8').getbest().download()
File "build\bdist.win32\egg\pafy\pafy.py", line 769, in download
os.rename(tempfname, fname)
WindowsError: [Error 183]


Resume Stream Download

I would like to resume a partial download, currently downloading only starts again at the beginning, even if the file is partially downloaded. I want this feature to support mobile applications were the connection may frequently drop.
I am willing to help add this feature, but currently have no time, and I am completely unfamiliar with PAFY's code base.

[Request] allow user to specify dev keys to avoid quota issues

Hi,

I'm trying to write a script that involves grabbing a lot of YouTube data at once. The result of this is that YouTube eventually gives an error 403 due to my client making too many requests. If I was able to specify a YouTube API key that Pafy would send along with its requests, YouTube Woodgeard the client much more leeway.

I'm going to look into trying to add this feature myself (I believe in giving what I can to open-source projects), but since I'm a newbie to Python, you shouldn't count on it. :/

Thanks for the awesome library!
--Matt

pafy.new('FAGL9gxhdHM') - error

pafy v 0.3.50

Can someone please check:

item = pafy.new('FAGL9gxhdHM')

I get an error:

Traceback (most recent call last):
   File "<pyshell#3>", line 1, in
     item = pafy.new ('FAGL9gxhdHM')
   File "C: \ Python27 \ lib \ site-packages \ pafy \ pafy.py", line 129, in new
     return Pafy (url, basic, gdata, signature, size, callback)
   File "C: \ Python27 \ lib \ site-packages \ pafy \ pafy.py", line 821, in __ init__
     self.fetch_basic ()
   File "C: \ Python27 \ lib \ site-packages \ pafy \ pafy.py", line 880, in fetch_basic
     self.process_streams ()
   File "C: \ Python27 \ lib \ site-packages \ pafy \ pafy.py", line 917, in process_streams
     adpt_streams = [Stream (z, self) for z in self.asm]
   File "C: \ Python27 \ lib \ site-packages \ pafy \ pafy.py", line 522, in __ init

     self._resolution = g.itags [self.itag] [0]
KeyError: u'272 '

synatx error

hi i'm using py v2.6.5
after pip install
when i'm trying to use ytdl it says there is syntax error

File "/usr/local/lib/python2.6/dist-packages/pafy.py", line 181
smap = [{k: v[0] for k, v in x.items()} for x in smap]
^
SyntaxError: invalid syntax

whould please explain whats the problem?!

running slow on grabbing info

hi there
why catching streams info is very slow. when i'm using -s parameter it takes about 15 seonds!
On the other hand downloading directly is much faster (e.g. when i'm using -b parameter)

URL problem on Windows.

When you parse the URL argument on Windows Terminal, argparser crop everything after the first & char.

So if you try to parse something like
http://www.youtube.com/watch?feature=player_detailpage&v=Pr0kBfJz9QE#t=28
ytdl will only get
http://www.youtube.com/watch?feature=player_detailpage
and this will cause an error.

128kbps audio only :[

Hey there,

Thanks for the awesome lib! Somehow Pafy shows/downloads 128kbps audios only.
I will use https://www.youtube.com/watch?v=F4MYdo7_shY as example below:

bash-3.2$  ytdl F4MYdo7_shY -t all 
Stream Type    Format Quality         Size            
------ ----    ------ -------         ----            
1      normal  mp4    [1280x720]      17 MB           
2      normal  webm   [640x360]        5 MB           
3      normal  mp4    [640x360]        6 MB           
4      normal  flv    [320x240]        4 MB           
5      normal  3gp    [320x240]        5 MB           
6      normal  3gp    [176x144]        1 MB           
7      video   m4v    [1920x1080]      7 MB           
8      video   webm   [1920x1080]      8 MB           
9      video   m4v    [1280x720]       5 MB           
10     video   webm   [720x480]        4 MB           
11     video   m4v    [854x480]        3 MB           
12     video   webm   [640x480]        2 MB           
13     video   m4v    [640x360]        1 MB           
14     video   webm   [480x360]        1 MB           
15     video   m4v    [426x240]        2 MB           
16     video   webm   [360x240]        1 MB           
17     video   m4v    [256x144]        1 MB           
18     audio   m4a    [128k]           3 MB           
19     audio   ogg    [128k]           3 MB           
bash-3.2$ 
>>> import pafy
>>> v = pafy.new("F4MYdo7_shY")
>>> v.audiostreams
[audio:m4a@128k, audio:ogg@128k]
>>> 

I used 3rd party tool to download 256kbps.
Also, we got 192kbps sound stream while downloading 720p+ with Pafy

Attaching related spectrograms:

at the gala soundtrack - 256kbps

at the gala soundtrack - 192kbps

at the gala soundtrack - 128kbps

I am using latest stable version of Pafy:

Python 2.7.5
Pafy==0.3.62

Thanks again and keep up the good work!

Running pafy script after multiple times (random) pafy didnt confirm I downloaded the video

let's say I created a basic web for converting youtube videos to gifs

this is my views in django code

from django.shortcuts import render
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response 
import pafy
from PIL import Image 
from moviepy.editor import *
import os

context = RequestContext(request)
    if request.GET:
         link = request.GET.get('link','')
    url = link
    try:
        video = pafy.new(url)
    except:
        return render_to_response("generated/invalid.html", context)
    video = video.getbest()
    if os.path.isfile(os.getcwd()+'\\static\\'+video.title+'.gif')==True:
        gifpath=video.title+'.gif'
        context_dict = {'staticpath':gifpath}
        return render_to_response("generated/generated.html", context_dict, context)
    video.download(quiet=False)
    clip = (VideoFileClip(os.getcwd()+"\\"+video.title+'.'+video.extension).resize(0.4))
    clip.write_gif(os.getcwd()+'\\static\\'+video.title+'.gif', fps=9, opt='optimizeplus', loop=0)
    gifpath=video.title+'.gif'
    context_dict = {'staticpath':gifpath}
    return render_to_response("generated/generated.html", context_dict, context)

it works fine, but after I convert 2-5 videos (it's random) it gives me this error,
capture1

I have to restart the django server to make it works again, strange!

the first request the terminal confirmed the video downloaded succesfully, in the 2nd request it didnt, but the video is downloaded and I can watch it. what do you think causing this? my code or the lib?

THANKS FOR YOUR TIME

Ogg Vorbis files are malformed

It seems that the Ogg Vorbis files are malformed or maybe need to be put into an Ogg container as it isn't possible to change any tags (artist, title, album, ..).

I can play the file with VLC, but when opening the files with EasyTag (software to change tags of several formats), there's an error message: Ogg Vorbis: bitstream doesn't contain vorbis data.

Another problem is that the default Android Audio Player doesn't recognize the ogg files even though it does support them

On the contrary, downloading the webm file (with pafy) and extracting the ogg part with avconv -i ./input.webm -vn -acodec copy ./output.ogg did create a normal ogg file that could be tagged and worked as intended. (even on Android)

(Just tested: The m4a files are recognized and can be tagged.)

IOError: no match for Go.sH(a,2)

Hi, please check this, thanks:

pafy.new('J0LzmoBory4')

Traceback (most recent call last):
File "<pyshell#33>", line 1, in
pafy.new('J0LzmoBory4')
File "build\bdist.win32\egg\pafy\pafy.py", line 129, in new
return Pafy(url, basic, gdata, signature, size, callback)
File "build\bdist.win32\egg\pafy\pafy.py", line 888, in init
s[0].url # forces signature decryption
File "build\bdist.win32\egg\pafy\pafy.py", line 726, in url
sig = _decodesig(s, self._parent.js_url) if s else None
File "build\bdist.win32\egg\pafy\pafy.py", line 474, in _decodesig
solved = _solve(mainfunction, js_url)
File "build\bdist.win32\egg\pafy\pafy.py", line 410, in _solve
raise IOError("no match for %s" % part)
IOError: no match for Go.sH(a,2)

IOError: no match for Go.sH(a,2) - Crashes on xGD6I8usrT4

def saveTrack(trackURL): 
  global trackLength
  video = pafy.new(trackURL, basic=False, signature=False)
  print("instance made")
  trackLength = video.length
  print("length found")
  audio = video.getbestaudio()
  print("best audio found")
  myfilename = "/mnt/sdcard/songs/song.ogg"
  audio.download(filepath=myfilename,quiet=True, callback=ETA) #fails here
  print("saved")

This fails with https://www.youtube.com/watch?v=xGD6I8usrT4 but works with the majority of other tracks

4k videos do not show all resolutions

See below but, videos with resolutions above 720p do not show up in resolution list. I am not sure if it is as intended.

url = "https://www.youtube.com/watch?v=cTQvYxELaFI"
vid = pafy.new(url)
vid.streams
[normal:mp4@1280x720, normal:mp4@1280x720-3D, normal:webm@640x360, normal:webm@640x360-3D, normal:mp4@640x360, normal:mp4@640x360-3D, normal:flv@320x240, normal:3gp@320x240, normal:3gp@176x144]

screen shot 2014-03-18 at 10 38 54 am

AttributeError: 'module' object has no attribute 'new'

Hi, I am getting the following error while running the example code from terminal

Traceback (most recent call last):
File "pafy.py", line 4, in
import pafy
File "/home/tricon/bikesh/Tutor/python/python_tutorial/youtube/pafy.py", line 8, in
video = pafy.new("F4MYdo7_shY")
AttributeError: 'module' object has no attribute 'new'

invalid characters in file name on windows

Dear creator of pafy,
thanks for open sourcing such a useful tool.
While downloading rhymes for my kid, found that few videos are having titles with characters which are invalid for file names.
temporarily fixed in my local copy for problematic characters (\ / : * ? " < > |) as of now
filetosave = filetosave.replace("?","").replace(""","")...;

Saw few examples on Stackoverflow for better solutions using regex and str.translate.
As I'm not aware of python much, could please add code remove/replace invalid characters.

Thanks

TypeError: cannot concatenate 'str' and 'NoneType' objects

Hello,
I'm sometimes getting errors like this one when trying to download a video :

Traceback (most recent call last):
  File "./download.py", line 43, in <module>
    best.download(quiet=QUIET, filepath = filename)
  File "/var/lib/stickshift/537000555973caa9b7000018/app-root/data/lib/python/site-packages/Pafy-0.3.42-py2.6.egg/pafy.py", line 694, in download
    response = g.opener.open(self.url)
  File "/var/lib/stickshift/537000555973caa9b7000018/app-root/data/lib/python/site-packages/Pafy-0.3.42-py2.6.egg/pafy.py", line 622, in url
    self._url = _make_url(self._rawurl, self._sig)
  File "/var/lib/stickshift/537000555973caa9b7000018/app-root/data/lib/python/site-packages/Pafy-0.3.42-py2.6.egg/pafy.py", line 464, in _make_url
    raw += "&signature=" + sig
TypeError: cannot concatenate 'str' and 'NoneType' objects

And if try again, it works like a charm.

m4a AAC audio streams do not play on iTunes Mac

When downloading any m4a audio stream for any video, it plays nicely in VLC and Google Play for Android. But when I add it to my library in iTunes for Mac, it is displayed in the list but tags do not show and the time/duration row says "Not available" (could be slightly different since I'm translating from Dutch: "Niet beschikbaar").

To be sure, I inspected it with MediaInfo as someone suggested on ##mac on the Freenode IRC server.

MediaInfo

iTunes should play AAC audio streams so I have no idea why it isn't. I also used the link that can be retrieved from a Stream object and downloaded it that way, but I get the same result.

Is there a way that I could fix this besides converting it again (which would probably lose even more quality)?

Upload Date/Time

Perusing through the documentation, past issues, and a little bit of the source code, I don't see any way to get the date/time that the video was uploaded.

I was able to work around it, but it might be useful for other people to be able to grab this type of information.

unicode file names

if i want to name the file, as the title plus some unicode string (in hebrow)

so i get the original name:
name = pafy.new('O5nWH10R_uI').getbestaudio().title

name:
u'\u05d0\u05d1\u05e8\u05d4\u05dd \u05d8\u05dc - \u05d0\u05dd \u05d0\u05ea \u05d4\u05d5\u05dc\u05db\u05ea'

now if i add to it the text u'אבג'
which is: u'\xe0\xe1\xe2'
name += u' אבג'
so now name is:
u'\u05d0\u05d1\u05e8\u05d4\u05dd \u05d8\u05dc - \u05d0\u05dd \u05d0\u05ea \u05d4\u05d5\u05dc\u05db\u05ea \xe0\xe1\xe2'

so the original name is in 4 characters for every letter, like \u05d0, and the new unicode text i added is 2 characters for every letter, like \xe0

any idea how to convert u'אבג' to same unicode format as the title?

Rename pypi package from Pafy to pafy

I suggest renaming below, but will not get offended, if you don't :]

:~ nameless$ pip freeze | grep pafy
:~ nameless$ pip freeze | grep -i pafy
Pafy==0.3.63
:~ nameless$ pip freeze | grep ^[a-z] | wc -l
      62
:~ nameless$ pip freeze | grep ^[A-Z] | wc -l
       4

UnicodeEncodeError

$ ytdl -b https://www.youtube.com/watch?v=ZHcU6eVDb2Y
Traceback (most recent call last):
File "/usr/bin/ytdl", line 170, in
main()
File "/usr/bin/ytdl", line 145, in main
download(vid, audio=args.a)
File "/usr/bin/ytdl", line 62, in download
print(dl_str.format(stream.filename, size))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 6-12: ordinal not in range(128)

This happens in the option -b : 'ytdl -b' and version Pafy-0.3.44

but with the version Pafy-0.3.42 work well.

Thanks.

Not working with VEVO videos.

The library can't open VEVO videos. Tested with these videos:

http://www.youtube.com/watch?v=qeMFqkcPYcg
http://www.youtube.com/watch?v=lWA2pjMjpBs

When I run pafy.Pafy(video_link), it gives me:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "./pafy.py", line 267, in __init__
    self.streams = [Stream(sm, opener, self.title, js) for sm in smap]
  File "./pafy.py", line 267, in <listcomp>
    self.streams = [Stream(sm, opener, self.title, js) for sm in smap]
  File "./pafy.py", line 147, in __init__
    streammap['sig'] = [_decodesig(streammap['s'][0], js)]
  File "./pafy.py", line 116, in _decodesig
    funcname = m.group(1)
AttributeError: 'NoneType' object has no attribute 'group'

AFAIK, it's caused because js doesn't have any g.s||... matching string.
It doesn't happen with non-VEVO files.

fetch description of youtube video

we are able to fetch title and other data of youtube video. but I didn't get any option to fetch description of video using pafy. can we fetch description using pafy?

bug report, video dTCNwgzM2rQ

Pafy 0.3.50
Python 2.7

when i try to get the video dTCNwgzM2rQ by:
item = pafy.new('https://www.youtube.com/watch?v=dTCNwgzM2rQ')
or
item = pafy.new('dTCNwgzM2rQ')
i am getting the following error:

Traceback (most recent call last):
File "<pyshell#3>", line 1, in
item = pafy.new('dTCNwgzM2rQ')
File "build\bdist.win32\egg\pafy\pafy.py", line 129, in new
return Pafy(url, basic, gdata, signature, size, callback)
File "build\bdist.win32\egg\pafy\pafy.py", line 801, in init
s[0].url # forces signature decryption
File "build\bdist.win32\egg\pafy\pafy.py", line 643, in url
enc_streams, js_url, funcs = get_js_sm(self._parent.videoid)
File "build\bdist.win32\egg\pafy\pafy.py", line 477, in get_js_sm
mainfunc = _get_mainfunc_from_js(javascript)
File "build\bdist.win32\egg\pafy\pafy.py", line 287, in _get_mainfunc_from_js
funcname = m.group(1)
AttributeError: 'NoneType' object has no attribute 'group'

is this a bug or am i doing something wrong?

Possible corruption of audio tags

Hello,

I'm using pafy for my personal project and everythink worked perfectly untill now.
I need to read and edit audio tags after I've downloaded the file and found quite a pretty tool for this - pytaglib.It's simple and doesn't care what format your files are. Just what I need.
The problem is that when I try to read tags from file it causes an OSError: Could not read file "...."
I tried with file, which isn't downloaded by pafy and it works.
So I guess there is some kind of corrupting the tags data, I don't know.

I'm not sure where the problem is: whether in pafy or pytaglib, so I decided to create an issue for both of them, hoping someone will come up with an idea.

Kind regards,
dragonaotor

PS: Great tool btw.Good work.

Fetch user all vidoes

Fetch user all videos https://www.youtube.com/user/daydayfree/videos
Is this can have?

KeyError: u'249'

Hello,
I'm getting an error while downloading a video using pafy :

>>> import pafy
>>> pafy.new("https://www.youtube.com/watch?v=4UgZ5FqdYIQ")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 131, in new
    return Pafy(url, basic, gdata, signature, size, callback)
  File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 925, in __init__
    self.fetch_basic()
  File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 986, in fetch_basic
    self._process_streams()
  File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 1023, in _process_streams
    adpt_streams = [Stream(z, self) for z in self.asm]
  File "/usr/local/lib/python2.7/dist-packages/pafy/pafy.py", line 607, in __init__
    self._resolution = g.itags[self.itag][0]
KeyError: u'249'

The error appears on a debian 7 wiyth python 2.7.3, I tried on a ubuntu 14.04 machine with python 2.7.6 (A c9.io workspace) and it works. Strange, seems to be only a minor version change...
Thanks in advance

Include start/end information in Playlist-data

You can set custom start and endtimes for videos in youtube playlists, they are luckily included in the playlist-json data:

In [44]: j = json.load(open('/tmp/list_ajax')) # list_ajax, simply g.urls['playlist'] downloaded

In [45]: v = j['video']

In [47]: [e for e in v if 'Summertime' in e['title']]
Out[47]: 
[{'views': '55.419.353',
  'added': '17.07.13',
  'endscreen_autoplay_session_data': 'feature=autoplay',
  'privacy': 'public',
  'time_created': 1396975613,
  'keywords': '"lana del rey" "cedric gervais" "summertime sadness" remix "official video"',
  'start': 4.46700000763,
  'duration': '3:46',
  'dislikes': 5555,
  'comments': '14.485',
  'title': "Lana Del Rey vs Cedric Gervais 'Summertime Sadness' Remix",
  'cc_license': False,
  'session_data': 'feature=playlist',
  'thumbnail': 'https://i.ytimg.com/vi/akhmS1D2Ce4/default.jpg',
  'description': "Lana Del Rey vs Cedric Gervais 'Summertime Sadness' Remix\n\nGet it on iTunes: http://smarturl.it/SummertimeGervais\n\nSubscribe to Spinnin' TV: http://bit.ly/SPINNINTV\n\nConnect with Cedric Gervais:\nhttp://www.cedricgervais.com\nhttp://facebook.com/cedgerv\nhttp://twitter.com/CedricGervais\nhttp://soundcloud.com/CedricGervais",
  'end': 226.0,
  'user_id': 'pDJl2EmP7Oh90Vylx0dZtA',
  'author': "Spinnin' Records",
  'encrypted_id': 'akhmS1D2Ce4',
  'likes': 252210,
  'category_id': 24,
  'is_hd': True,
  'rating': 5.0,
  'is_cc': False,
  'length_seconds': 226}]

These start and end keys do not exist in the json data if they are not set. My proposal, include them anyways but with start set to 0 and end to length_seconds.

I will probably submit a pull-request in the next hours/day(s), since I need that.

Print special characters

When Pafy try's download this video:
AGIR - "Alma Gémea" - http://www.youtube.com/watch?v=XCBygZhSEws
Because the name of video have a special character "é", the download fails.

My solution until now is:
sudo nano /usr/local/lib/python2.7/dist-packages/pafy.py

comment line63

print "-Downloading '{}' [{:,} Bytes]".format(self.filename, total)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.