本文整理匯總了Python中pafy.new方法的典型用法代碼示例。如果您正苦於以下問題:Python pafy.new方法的具體用法?Python pafy.new怎麽用?Python pafy.new使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類pafy
的用法示例。
在下文中一共展示了pafy.new方法的10個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: download_yt_video
# 需要導入模塊: import pafy [as 別名]
# 或者: from pafy import new [as 別名]
def download_yt_video(queue_item, dl_dir, channel_conf):
url = queue_item["link"]
dl_dir = dl_dir + channel_conf["name"]
try:
video = pafy.new(url)
streams = video.streams
#for s in streams:
#print(s.resolution, s.extension, s.get_filesize, s.url)
best = video.getbest(preftype=channel_conf["preferred_extension"])
filepath = dl_dir + "/"+ queue_item["yt_videoid"] + "." + channel_conf["preferred_extension"]
#TODO: implement resolution logic from config, currently downloading best resolution
best.download(filepath=filepath, quiet=False)
except:
pass
# TODO: check YT alternate URL for video availability
# TODO: print and log exceptions
示例2: youtube_download
# 需要導入模塊: import pafy [as 別名]
# 或者: from pafy import new [as 別名]
def youtube_download(self, url, profile, mesg):
try:
if profile in mesg:
sys.exit()
else:
video = new(url)
get_vid = video.getbest(preftype="mp4")
#dl = get_vid.download(quiet=False, filepath=self.__settings.SITE_PATH)
msg = " \
\n [+] Judul Video: %s \n \
\n[+] Uploader: %s \n \
\n[+] Durasi: %s \n \
\n[+] Link Download: %s%s.%s \n \
\n[+] File video akan dihapus 1 menit lagi. \n \
" % (video.title, video.author, video.duration, self.__settings.SITE_URL, \
video.title.replace(" ", "%20"), get_vid.extension)
self.group.sendImageWithURL(video.thumb)
self.group.sendMessage(msg)
except Exception:
self.group.sendMessage("[+] Sory broh!, URL youtube tidak valid! [+]")
示例3: download_audios
# 需要導入模塊: import pafy [as 別名]
# 或者: from pafy import new [as 別名]
def download_audios(self):
self._set_conf()
for link in self.links:
video = pafy.new(link)
best_audio = self._get_best_audio(video)
filename = best_audio.filename
if not best_audio:
# TODO: Add proper logger.
continue
if self._should_not_override(filename):
# TODO: Add proper logger.
continue
best_audio.download(
quiet=not self.show_download_progress,
filepath=self.path_to_save
)
示例4: download_video
# 需要導入模塊: import pafy [as 別名]
# 或者: from pafy import new [as 別名]
def download_video(self, id, file_path):
file_full_path = os.path.join(file_path, "{}.{}".format(id, 'mp4'))
if os.path.exists(file_full_path):
self.log('[Exist][video][{}]'.format(file_full_path))
else:
video = pafy.new(id)
best = video.getbest(preftype="mp4")
r = self.session.get(best.url)
os.makedirs(file_path, exist_ok=True)
with open(file_full_path, "wb") as code:
code.write(r.content)
self.log('[Finish][video][{}]'.format(file_full_path))
示例5: cargarurl
# 需要導入模塊: import pafy [as 別名]
# 或者: from pafy import new [as 別名]
def cargarurl(self):
"""
Método encargado de llamar al método cargarInfo en un
hilo distinto
"""
self.vista.button.config(state=DISABLED)
self.vista.bvideo.config(state=DISABLED)
self.vista.baudio.config(state=DISABLED)
self.vista.bborrar.config(state=DISABLED)
if platform.system() == 'Windows':
self.vista.config(cursor="wait")
if "facebook" in self.vista.url.get():
self.t = threading.Thread(target=self.cargarFB)
self.t.start()
else:
try:
self.recursoPL = pafy.get_playlist(self.vista.url.get())
self.t = threading.Thread(target=self.cargarPlayList)
self.t.start()
except ValueError as e:
try:
self.recurso = pafy.new(self.vista.url.get())
self.t = threading.Thread(target=self.cargarInfo)
self.t.start()
except ValueError as e:
mensaje = "La url es inválida o no se encuentra conectado "
mensaje += "a internet, intentelo nuevamente."
msg.showerror("Error", mensaje)
self.vista.button.config(state=NORMAL)
self.vista.bvideo.config(state=NORMAL)
self.vista.baudio.config(state=NORMAL)
self.vista.bborrar.config(state=NORMAL)
self.vista.config(cursor="")
示例6: download
# 需要導入模塊: import pafy [as 別名]
# 或者: from pafy import new [as 別名]
def download(directory, youtube_id, clear=False):
"""Download the audio of a YouTube video.
The audio is downloaded in the highest available quality. Progress is
printed to `stdout`. The file is named `youtube_id.m4a`, where
`youtube_id` is the 11-character code identifiying the YouTube video
(can be determined from the URL).
Parameters
----------
directory : str
The directory in which to save the downloaded audio file.
youtube_id : str
11-character video ID (taken from YouTube URL)
clear : bool
If `True`, it deletes the downloaded video. Otherwise it downloads
it. Defaults to `False`.
"""
filepath = os.path.join(directory, '{}.m4a'.format(youtube_id))
if clear:
os.remove(filepath)
return
if not PAFY_AVAILABLE:
raise ImportError("pafy is required to download YouTube videos")
url = 'https://www.youtube.com/watch?v={}'.format(youtube_id)
video = pafy.new(url)
audio = video.getbestaudio()
audio.download(quiet=False, filepath=filepath)
示例7: scrape
# 需要導入模塊: import pafy [as 別名]
# 或者: from pafy import new [as 別名]
def scrape(query, include, exclude, quiet, overwrite):
"""Search YouTube and download audio from discovered videos."""
# Search YouTube for videos.
url = 'http://youtube.com/results?' + urlencode({'search_query': query})
html = urlopen(url).read().decode('utf-8')
video_ids = re.findall(r'href=\"\/watch\?v=(.{11})', html)
# Go through all found videos.
for video_id in video_ids:
# Fetch metadata and available streams.
video = pafy.new(video_id)
# Collect video metadata.
metadata = video.keywords + [
video.title, video.author, video.description, video.category
]
haystack = ' '.join(metadata).lower()
# Don't download audio if video lacks a required term in its metadata.
if include:
if all(w not in haystack for w in include):
continue
# Don't download audio if video has a forbidden term in its metadata.
if exclude:
if any(w in haystack for w in exclude):
continue
# Always prefer highest quality audio.
audio = video.getbestaudio()
# Skip existing files.
if os.path.isfile(audio.filename) and not overwrite:
continue
# Download audio to working directory.
audio.download(quiet=quiet)
示例8: youtube_stream_link
# 需要導入模塊: import pafy [as 別名]
# 或者: from pafy import new [as 別名]
def youtube_stream_link(video_url):
video = pafy.new(video_url)
best_video = video.getbest()
best_audio = video.getbestaudio()
audio_streaming_link = best_audio.url
video_streaming_link = best_video.url
return audio_streaming_link, video_streaming_link
示例9: run
# 需要導入模塊: import pafy [as 別名]
# 或者: from pafy import new [as 別名]
def run(message, matches, chat_id, step):
from_id = message['from']['id']
if step == 0:
video = pafy.new(matches)
allstreams = video.allstreams
user_steps[from_id] = {"name": "Youtube", "step": 0, "data": []}
user_steps[from_id]['video'] = video
show_keyboard = {'keyboard': [], 'selective': True}
counter = 1
for s in allstreams:
if s.mediatype == "normal":
show_keyboard['keyboard'].append(
[str(counter) + ". " + s.quality + " | " + s.extension + " | " + str(sizeof_fmt(s.get_filesize()))])
user_steps[from_id]['data'].append(s)
counter += 1
if s.mediatype == "audio":
show_keyboard['keyboard'].append([str(
counter) + ". (Audio " + s.bitrate + " ) | " + s.extension + " | " + str(
sizeof_fmt(s.get_filesize()))])
user_steps[from_id]['data'].append(s)
counter += 1
user_steps[from_id]['step'] += 1
return [Message(chat_id).set_text("*Choose a Format :*", parse_mode="Markdown",
reply_to_message_id=message['message_id'], reply_markup=show_keyboard)]
elif step == 1:
try:
video = user_steps[from_id]['video']
best = user_steps[from_id]['data'][int(message['text'].split(".")[0]) - 1]
hide_keyboard = {'hide_keyboard': True, 'selective': True}
await sender(
Message(chat_id).set_text("*Please Wait*\n_I am Retrieving The Video_", parse_mode="markdown",
reply_to_message_id=message['message_id'], reply_markup=hide_keyboard))
if best.get_filesize() < 49000000:
if best.mediatype == "normal":
del user_steps[from_id]
filepath = "tmp/{}.{}".format(uuid.uuid4(), best.extension)
await downloader(best.url, filepath)
return [Message(chat_id).set_document(filepath, reply_markup=hide_keyboard)]
if best.mediatype == "audio":
filepath = "tmp/{}.{}".format(uuid.uuid4(), best.extension)
await downloader(best.url, filepath)
del user_steps[from_id]
return [Message(chat_id).set_audio(filepath, performer="@Siarobot", title=video.title,
reply_markup=hide_keyboard)]
result = "*Click on the bottom link to Download*\n[{}]({})".format(video.title, best.url)
del user_steps[from_id]
return [Message(chat_id).set_text(result, disable_web_page_preview=True,
reply_to_message_id=message['message_id'], parse_mode="Markdown",
reply_markup=hide_keyboard)]
except Exception as e:
print(e)
del user_steps[from_id]
hide_keyboard = {'hide_keyboard': True, 'selective': True}
return [Message(chat_id).set_text("*Something Wrong*\n_Try Again!_", parse_mode="markdown",
reply_to_message_id=message['message_id'], reply_markup=hide_keyboard)]
示例10: get_video_data
# 需要導入模塊: import pafy [as 別名]
# 或者: from pafy import new [as 別名]
def get_video_data(channel_id):
yt_rss_url = "https://www.youtube.com/feeds/videos.xml?channel_id=" + channel_id
feed = fp.parse(yt_rss_url)
channel_lang = feed["feed"]["title_detail"]["language"]
print(feed["feed"])
entries = feed["entries"]
channels_timestamps = "channels_timestamps.csv"
# clear any existing queue before start
queue = []
# read contents of channels_timestamps.csv, create list object of contents
ct = open(channels_timestamps, "r")
ctr = ct.read().split("\n")
ct.close()
ctr_line = []
channel_found = False
# check if channel ID is found in channels_timestamps.csv
for line in ctr:
line_list = line.split(',')
if channel_id == line_list[0]:
channel_found = True
ctr_line = line
break
if not channel_found:
print("new channel added to config: " + channel_id)
print(channel_id)
# iterate through video entries for channel, parse data into objects for use
for pos, i in enumerate(reversed(entries)):
published = i["published"]
updated = i["updated"]
if not channel_found:
# add the video to the queue
queue.append(i)
ctr_line = str(channel_id + "," + published + "," + updated + '\n')
# add the new line to ctr for adding to channels_timestamps later
ctr.append(ctr_line)
channel_found = True
# if the channel exists in channels_timestamps, update "published" time in the channel line
else:
published_int = utils.convert_timestamp(published)
ctr_line_list = ctr_line.split(",")
line_published_int = utils.convert_timestamp(ctr_line_list[1])
if published_int > line_published_int:
# update the timestamp in the line for the channel in channels_timestamps,
ctr.remove(ctr_line)
ctr_line = str(channel_id + "," + published + "," + updated + '\n')
ctr.append(ctr_line)
# and add current videos to queue.
queue.append(i)
print(published)
# write the new channels and timestamps line to channels_timestamps.csv
ct = open(channels_timestamps, "w")
for line in ctr:
if line != '':
ct.write(line + "\n")
ct.close()
return queue, channel_lang