Hướng dẫn tải video youtube trên Linux/Ubuntu bằng Perl Script

Thông thường, khi bạn muốn xem một video Youtube, bạn phải sử dụng Adobe Flash hoặc HTML5 trong trình duyệt như Firefox, Chrome (Chromium), Opera hoặc Safari. Adobe Flash nó vô cùng không hiệu quả, một lỗ hổng bảo mật rất lớn và nổi tiếng là lỗi. Một vấn đề nữa là tốc độ buffering chậm liên tục của youtube khi được giới hạn bởi ISP của bạn. Thật bực bội nếu bạn liên tục chờ đợi video đệm trong một phiên tương tác.

Bài viết này chiasefree.com hướng dẫn các bạn tải video youtube dành cho Linux/Ubuntu.

Hướng dẫn tải video youtube trên Linux/Ubuntu bằng Perl Script
Hướng dẫn tải video youtube trên Linux/Ubuntu bằng Perl Script

Cách khác là sử dụng tập lệnh để tải xuống các video của bạn để xem sau. Sử dụng Curl có thể hoặc không thể nhanh hơn sau đó nhấp đèn flash trong trình duyệt tùy thuộc vào gương YouTube mà bạn kết nối. Vì vậy, ý tưởng là tải trước một loạt video và khi bạn đã sẵn sàng để xem chúng, chúng sẽ phát ở chất lượng cao nhất mà không có bộ đệm YouTube dừng ngay. Chúng tôi muốn xem video bằng cách sử dụng VLC sử dụng thời gian CPU ít hơn sau đó flash và có thể phát video ở tốc độ cao hơn 1x. Trong thực tế, chúng tôi xem hầu hết tất cả các vids của chúng tôi ở 2x (sử dụng + phím trên bàn phím bên phải).

Perl Script bản mới nhất: 0.58

  • Đảm bảo cURL theo sau chuyển hướng.
  • Chuyển từ wget sang cURL để tải xuống video. CURL được cài đặt trên nhiều hệ thống theo mặc định.
  • Nếu tải xuống không nhận được thông báo, “Video có thể không khả dụng ở độ phân giải yêu cầu hoặc có thể được sao chép bảo vệ.” In để giúp người sử dụng xác định vấn đề.
  • Thêm một vòng lặp để thử một máy nhân bản khác nếu URL không phân tích chính xác.
  • Viết lại mã để sử dụng các biện pháp bảo mật nghiêm ngặt và tồi tệ của perl.
  • Chọn loại tệp và tiện ích mở rộng tệp như mp4, webm, avi hoặc flv.
  • Chọn độ phân giải như độ phân giải chuẩn 720p, 640 hoặc thậm chí 144p (176×144).
  • Đối với các nhà phát triển, chúng tôi đã thêm một tùy chọn DEBUG để giúp những người sửa đổi script hoặc nếu bạn đang cố gắng để làm cho bạn sở hữu youtube downloader.

Ưu điểm của Perl Script 

AdBlock Plus và NoScript an toàn, Không cần Adobe Flash:

Để tải xuống video Youtube, chỉ cần cắt và dán URL từ thanh URL của trình duyệt. Bạn không cần bắt đầu video hoặc bất cứ thứ gì. Trong thực tế, nếu bạn có NoScript bạn thậm chí không phải cho phép java script trên trang web Youtube. Bạn chỉ cần liên kết và dán nó sau script. Đơn giản và dễ dàng.

Tốc độ tải không giới hạn:

Không có giới hạn tỷ lệ tải xuống với URL mà chúng tôi trích xuất từ ​​trang HTML. Các video sẽ tải xuống nhanh như các máy chủ bộ nhớ cache Youtube sẽ gửi dữ liệu. Tốc độ chủ yếu phụ thuộc vào sự phổ biến của video; Yêu cầu nhất cho video được đưa vào các máy chủ lưu trữ băng thông cao nhất băng thông. Sử dụng một máy chủ thử nghiệm trên Linode (Xen VPS Hosting) chúng tôi dễ dàng thấy 24 MB / giây tải. Giới hạn tải lên và tải xuống tối đa trên máy chủ Linode là 45 megabyte / giây. BTW, Linode nhận được 10 trong số 10 đối với chất lượng tổng thể theo ý kiến ​​của chúng tôi.

Không quảng cáo:

Tập lệnh sẽ không tải bất kỳ quảng cáo hoặc quảng cáo nào giống như những gì bạn sẽ thấy nếu bạn sử dụng trình duyệt để xem các video flash. Lý do là quảng cáo không phải là một phần của video. Chúng tôi không làm bất cứ điều gì để loại bỏtất cả quảng cáo . Khi bạn nhìn thấy quảng cáo trên Youtube, video thực sự bị tạm dừng và quảng cáo được phủ lên phía trên cửa sổ video. Khi quảng cáo hoàn thành lớp phủ sẽ bị xóa và video không bị tạm dừng.

Bắt đầu

Tập lệnh tải về trên web được viết bằng Perl và có thể chạy trên Linux, Mac OSX, OpenBSD, FreeBSD hoặc bất kỳ hệ điều hành nào hỗ trợ Perl.

CURL, lưu ý sự viết hoa, là sự phụ thuộc duy nhất bạn cần phải cài đặt trên hệ thống của bạn và hệ nhị phân cần phải có trong $PATH của shell. CURL hữu ích không chỉ cho tập lệnh perl này mà còn cho bất kỳ tập lệnh nào bạn có thể làm về tương lai. Gói cURL tiêu chuẩn sẽ cho phép bạn tải xuống các video bằng HTTP hoặc HTTPS. Để dễ dàng hơn, chúng tôi bao gồm các dòng sau để cài đặt cURL bằng trình quản lý gói của hệ điều hành. Bạn có thể đã cài đặt hệ thống. Gõ “curl” cho đường dẫn đầy đủ đến nhị phân cURL.

## Ubuntu Linuxapt-get install curl## Redhat Linuxyum install curl## FreeBSDpkg install curl## OpenBSD pkg_add -i curl

Nếu như bạn cài đặt Curl không được thì bạn có thể cài Wget bằng cách sử dụng lệnh dưới đây:

sudo apt-get install wget

Youtube Download Perl script

Để sử dụng script, sao chép và dán mã perl từ hộp văn bản sau vào tệp tin. Chúng ta sẽ đặt tên cho scrip này là  youtube_download.pl hoặc bạn có thể đặt tên nó là bất cứ thứ gì bạn muốn.

#!/usr/bin/perl -Tuse strict;use warnings;###  Calomel.org  ,:,  Download Youtube videos##    Script Name : youtube_download.pl##    Version     : 0.58##    Valid from  : March 2016##    URL Page    : https://calomel.org/youtube_wget.html##    OS Support  : Linux, Mac OSX, OpenBSD, FreeBSD#                `:`## Two arguments##    $1 Youtube URL from the browser##    $2 prefix to the file name of the video (optional)#############  options  ########################################### Option: what file type do you want to download? The string is used to search# in the youtube URL so you can choose mp4, webm, avi or flv.  mp4 is the most# compatable and plays on android, ipod, ipad, iphones, vlc and mplayer.my $fileType = "mp4";# Option: what visual resolution or quality do you want to download? List# multiple values just in case the highest quality video is not available, the# script will look for the next resolution. You can choose "itag=22" for 720p,# "itag=18" which means standard definition 640x380 and "itag=17" which is# mobile resolution 144p (176x144). The script will always prefer to download# the first listed resolution video format from the list if available.my $resolution = "itag=22,itag=18";# Option: How many times should the script retry if the download fails?my $retryTimes = 2;# Option: turn on DEBUG mode. Use this to reverse engineering this code if you are# making changes or you are building your own youtube download script.my $DEBUG=0;################################################################## initialize global variables and sanitize the path$ENV{PATH} = "/bin:/usr/bin:/usr/local/bin:/opt/local/bin";my $prefix = "";my $retry = 1;my $retryCounter = 0;my $user_url = "";my $user_prefix = "";# collect the URL from the command line argumentchomp($user_url = $ARGV[0]);my $url = "$1" if ($user_url =~ m/^([a-zA-Z0-9\_\-\&\?\=\:\.\/]+)$/ or die "\nError: Illegal characters in YouTube URL\n\n" );# declare the user defined file name prefix if specifiedif (defined($ARGV[1])) {   chomp($user_prefix = $ARGV[1]);   $prefix = "$1" if ($user_prefix =~ m/^([a-zA-Z0-9\_\-\.\ ]+)$/ or die "\nError: Illegal characters in filename prefix\n\n" );}# if the url down below does not parse correctly we start over heretryagain:# make sure we are not in a tryagain loop by checking the counterif ( $retryTimes < $retryCounter ) {   print "\n\n Stopping the loop because the retryCounter has exceeded the retryTimes option.";   print "\n The video may not be available at the requested resolution or may be copy protected.\n\n";   print "\nretryTimes counter = $retryTimes\n\n" if ($DEBUG == 1);   exit;}# download the html from the youtube page containing the page title and video# url. The page title will be used for the local video file name and the url# will be sanitized to download the video.my $html = `curl -sS -L --compressed -A "Mozilla/5.0 (compatible)" "$url"`  or die  "\nThere was a problem downloading the HTML page.\n\n";# format the title of the page to use as the file namemy ($title) = $html =~ m/<title>(.+)<\/title>/si;$title =~ s/[^\w\d]+/_/g or die "\nError: we could not find the title of the HTML page. Check the URL.\n\n";$title = lc ($title);$title =~ s/_youtube//ig;$title =~ s/^_//ig;$title =~ s/_amp//ig;$title =~ s/_39_s/s/ig;$title =~ s/_quot//ig;# filter the URL of the video from the HTML pagemy ($download) = $html =~ /"url_encoded_fmt_stream_map"(.*)/ig;# Print the raw separated strings in the HTML page#print "\n$download\n\n" if ($DEBUG == 1);# This is where we loop through the HTML code and select the file type and# video quality. my @urls = split(',', $download);OUTERLOOP:foreach my $val (@urls) {#   print "\n$val\n\n";    if ( $val =~ /$fileType/ ) {       my @res = split(',', $resolution);       foreach my $ress (@res) {         if ( $val =~ /$ress/ ) {         print "\n  html to url separation complete.\n\n" if ($DEBUG == 1);         print "$val\n" if ($DEBUG == 1);         $download = $val;         last OUTERLOOP;         }       }    }}# clean up by translating url encoding and removing unwanted stringsprint "\n  Start regular expression clean up...\n" if ($DEBUG == 1);$download =~ s/\%([A-Fa-f0-9]{2})/pack('C', hex($1))/seg;$download =~ s/sig=/signature=/g;$download =~ s/\\u0026/\&/g;$download =~ s/(type=[^&]+)//g;$download =~ s/(fallback_host=[^&]+)//g;$download =~ s/(quality=[^&]+)//g;$download =~ s/&+/&/g;$download =~ s/&$//g;$download =~ s/%2C/,/g;$download =~ s/%252F/\//g;$download =~ s/^:"url=//g;$download =~ s/\"//g;$download =~ s/\?itag=22&/\?/;# print the URL before adding the page title.print "\n  The download url string: \n\n$download\n" if ($DEBUG == 1);# check for &itag instances and either remove extras or add an additionalmy $counter1 = () = $download =~ /&itag=\d{2,3}/g;print "\n  number of itag= (counter1): $counter1\n" if ($DEBUG == 1);if($counter1 > 1){ $download =~ s/&itag=\d{2,3}//; }if($counter1 == 0){ $download .= '&itag=22' }# save the URL starting with http(s)... my ($youtubeurl) = $download =~ /(https?:.+)/;# is the URL in youtubeurl the variable? If not, go to tryagain above.if (!defined $youtubeurl) {    print "\n URL did not parse correctly. Let's try another mirror...\n";    $retryCounter++;    sleep 2;    goto tryagain;}# collect the title of the pagemy ($titleurl) = $html =~ m/<title>(.+)<\/title>/si;$titleurl =~ s/ - YouTube//ig;# combine file variables into the full file namemy $filename = "unknown";$filename = "$prefix$title.$fileType";# url title to url encoding. all special characters need to be converted$titleurl =~ s/([^A-Za-z0-9\+-])/sprintf("%%%02X", ord($1))/seg;# combine the youtube url and title string$download = "$youtubeurl\&title=$titleurl";# Process check: Are we currently downloading this exact same video? Two of the# same download processes will overwrite each other and corrupt the file.my $running = `ps auwww | grep [c]url | grep -c "$filename"`;print "\n  Is the same file name already being downloaded? $running" if ($DEBUG == 1);if ($running >= 1)  {   print "\n  Already $running process, exiting." if ($DEBUG == 1);   exit 0;  };# Print the long, sanitized youtube url for testing and debuggingprint "\n  The following url will be passed to curl:\n" if ($DEBUG == 1);print "\n$download\n" if ($DEBUG == 1);# print the file name of the video being downloaded for the user print "\n Download:   $filename\n\n" if ($retryCounter == 0 || $DEBUG == 1);# print the itag quantity for testingmy $counter2 = () = $download =~ /&itag=\d{2,3}/g;print "\n  Does itag=1 ?  $counter2\n\n" if ($DEBUG == 1);if($counter2 < 1){ print "\n URL did not parse correctly (itag).\n"; exit;}# Background the script before the download starts. Use "ps" if you need to# look for the process running or use "ls -al" to look at the file size and# date.fork and exit;# Download the video, resume if necessarysystem("curl", "-sSRL", "-A 'Mozilla/5.0 (compatible)'", "-o", "$filename", "--retry", "5", "-C", "-", "$download");# Print the exit error codeprint "\n  exit error code: $?\n" if ($DEBUG == 1);# Exit Status: Check if the file exists and we received the correct error code# from the curl system call. If the download experienced any problems the# script will run again and try to continue the download until the retryTimes# count limit is reached.if( $? == 0 && -e "$filename" && ! -z "$filename" )   {      print "\n  Finished: $filename\n\n" if ($DEBUG == 1);   } else   {      print STDERR "\n  FAILED: $filename\n\n" if ($DEBUG == 1);      $retryCounter++;      sleep $retryCounter;      goto tryagain;   }#### EOF #####

 

Thực thi tập tin (wxecutable), bằng cách sử dụng lệnh sau đây:

chmod 755 youtube_download.pl

Cách sử dụng Perl Script để tải Video trên Youtube

user@chiasefree$ ./youtube_download.pl "https://www.youtube.com/watch?v=ahfJ0HkLcgM" ## Download: nhung_bai_hat_cover_hay_nhat_JFla_2017.mp4 Tự động tải trong background ##

Convert video youtube tới mp3 hoặc ogg

## Convert the audio from a Youtube video to mp3 or ogg, audio only.## download the video. (Same link to the Fallout 4 video as above)user@machine$ ./youtube_download.pl "https://www.youtube.com/watch?v=0YnyQTSALCE" Downloading:  fallout_4_the_wanderer_trailer.mp4## Convert video to mp3, audio onlyuser@machine$ avconv -i fallout_4_the_wanderer_trailer.mp4 -vn -ab 128 fallout_4_the_wanderer_trailer.mp3## Convert video to ogg, audio onlyuser@machine$ avconv -i fallout_4_the_wanderer_trailer.mp4 -vn -ab 128 fallout_4_the_wanderer_trailer.ogg## Extract video's audio to aac, audio only (best quality)user@machine$ avconv -i fallout_4_the_wanderer_trailer.mp4 -map 0:1 -c:a copy fallout_4_the_wanderer_trailer.aac

 

Chiasefree

I am passionate about blogging and sharing good tips to readers, I like random web programming. Never back down.

Đăng nhận xét (0)
Mới hơn Cũ hơn