python爬虫脚本下载YouTube视频

python爬虫脚本下载YouTube视频

爬虫
python
YouTube视频

工作环境:

  • python 2.7.13

  • pip

  • lxml, 安装 pip install lxml,主要用xpath查找节点,可以使用re模块代替

  • pytube, 安装 pip install pytube

  • ***工具

参考:

源码:

  1. # coding: utf-8 

  2. __author__ = "zwzhou" 

  3. __date__ = "2017-03-19" 


  4. import urllib2 

  5. from pytube import YouTube 

  6. from pprint import pprint 

  7. from lxml import etree 

  8. import sys,getopt 


  9. def getHtml(url): 

  10. user_agent='Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.13 (KHTML, like Gecko) Chrome/24.0.1284.0 Safari/537.13' 

  11. headers={'User-Agent':user_agent} 

  12. request=urllib2.Request(url,headers=headers) 

  13. response=urllib2.urlopen(request) 

  14. html=response.read() 

  15. return html 


  16. def getUrl(html): 

  17. global savepath 

  18. global maxNumber 

  19. global timeThreshold 

  20. global cur_count 

  21. global videoLists 

  22. tree=etree.HTML(html) 

  23. urllist=tree.xpath(u'//div[@class="thumb-wrapper"]/a/@href') 

  24. #print urllist 

  25. urllist_time=tree.xpath(u'//div[@class="thumb-wrapper"]/a/span/span/text()') 


  26. baseurl=r'https://www.youtube.com' 

  27. for (item_name,item_length) in zip(urllist,urllist_time): 

  28. #print item_name 

  29. #print item_length 

  30. try: 

  31. yt = YouTube(baseurl+item_name) 

  32. except: 

  33. print "Some thing wrong about the authority" 


  34. print("video name:"+yt.filename) 

  35. print("video time:"+item_length) 

  36. if yt.filename in videoLists: # 文件已经存在 

  37. print "This video has been downloaded!" 

  38. else: 

  39. if checktime(item_length): 

  40. video = yt.filter('mp4')[-1] 

  41. print("Now is loading %s------------>"%yt.filename) 

  42. video.download(savepath) 

  43. print("--------------->%sVideo is loaded!"%yt.filename) 

  44. cur_count+=1 

  45. videoLists.append(yt.filename) 

  46. if cur_count >= maxNumber:# 达到要求 

  47. print('There are %d videos downloaded!This task is completed!'%maxNumber) 

  48. # TODO: if necessary, the videoLists can be logged 

  49. sys.exit()  

  50. else: 

  51. print 'This video is too long and it will not be downloaded, just be ignored!' 

  52. if urllist: 

  53. getUrl(baseurl+urllist[0]) #下一个页面 



  54. def checktime(timelength): 

  55. global timeThreshold 

  56. strs=timelength.split(':') 

  57. time =int(strs[0])*60+int(strs[1]) 

  58. if time< timeThreshold: 

  59. return True 

  60. else: 

  61. return False 


  62. def usage(): 

  63. print ''' 

  64. usage: python dl_youtube [option] [arg] 

  65. options and args: 

  66. -s : download path 

  67. -t : time threshold of the video to be loaded, in seconds 

  68. -u : start url which to be crawled, it can be set more than one time 

  69. -n : when downloading is stop, i.e. how many videos will be downloaded, default is 10000. 

  70. -h : print this help message 

  71. ''' 


  72. if __name__ == "__main__": 

  73. start_urls=['https://www.youtube.com/watch?v=TThzH_sJo6o'] 

  74. videoLists=[] # 保存文件名,防止重复下载 

  75. # 初始值 

  76. savepath=r"D://MyDownloads" 

  77. maxNumber=10000 

  78. timeThreshold=240 

  79. cur_count=0 


  80. opts,args=getopt.getopt(sys.argv[1:],'hs:t:n:u:') 

  81. for op,value in opts: 

  82. if op == "-s": # 下载路径,如默认 D://MyDownloads 

  83. savepath=value 

  84. elif op == '-t': # 时常限制,默认240s 

  85. timeThreshold =int(value) 

  86. elif op == "-h": # help 

  87. usage() 

  88. sys.exit() 

  89. elif op == '-n': 

  90. maxNumber=int(value) 

  91. elif op == '-u': # 初始的搜索链接 

  92. start_urls.append(value) 


  93. for item in start_urls: 

  94. html = getHtml(item) 

  95. getUrl(html) 


使用

  1. python dl_youtube.py -n 10 -s D://MyDownloads -t 600 -u https://www.youtube.com/watch?v=TThzH_sJo6o 

将从页面 https://www.youtube.com/watch?v=TThzH_sJo6o 开始搜索下载10段时长小于6分钟的video保存到D://MyDownloads文件夹中。

上一篇:我给女朋友讲编程html系列(4) -- html常用简单标签


下一篇:setAttribute设置无效