【问题标题】:python- youtube. Get url video list蟒蛇 - youtube。获取url视频列表
【发布时间】:2016-04-26 02:11:50
【问题描述】:

我正在使用 python 2.7。 我想用特定 youtube 列表中的视频列表创建一个 txt:

example list

我写的(我是 Python 的新手):

from bs4 import BeautifulSoup
import urllib2
import re 


url='https://www.youtube.com/playlist?list=PLYjSYQBFeM-zQeZFpWeZ_4tnhc3GQWNj8'
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())

href_tags = soup.find_all(href=True)

ff = open("C:/exp/file.txt", "w")

然后这工作了:

for i in href_tags:
    ff.write(str(i))
ff.close()

但是,因为我只想保留那些里面有“手表”的人,所以我尝试了:

for i in href_tags:
    if re.findall('watch',str(i))=='watch':
        ff.write(str(i))
ff.close()

但我得到了一个空的 txt。

我怎样才能只保留链接?有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python youtube beautifulsoup urllib2


    【解决方案1】:
    # This code will work if you're are willing to use a newer version of Python
    from bs4 import BeautifulSoup
    import requests
    
    class Playlist():
        def __init__(self, playListUrl):
            self._playListUrl = playListUrl
    
            # This will take the html text from Youtube playList url and stores it in a variable called html-doc.
            self._htmldoc = requests.get(str(self._playListUrl)).text
            self._soup = BeautifulSoup(self._htmldoc, 'html.parser')
    
            # This will create a list of all the titles and the youtube url videos using the html-doc.
            self._rawList = self._soup('a', {'class': 'pl-video-title-link'})
    
            # This will loop through a list of titles and Youtube urls and formats it nicely for you.
            for link in self._rawList:
                print('{0}'.format(link.string) + 'http://youtube.com' + '{0}'.format(link.get('href')))
    
    # To use this class all you got to do is:
    # 1 - Create a new object to use the class..
    # 2- put a youtube playlist url where it is shown below..
    # 3- Run it, and enjoy.
    objPlaylist = Playlist('put Youtube playlist url here')
    

    【讨论】:

      【解决方案2】:

      一个简单的in 应该这样做:

      for i in href_tags:
          if 'watch' in str(i):
              ff.write(str(i))
          ff.close()
      

      【讨论】:

        【解决方案3】:

        另外,您可以使用包subprocess 安装youtube-dl

        youtube-dl https://www.youtube.com/playlist?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc --yes-playlist --get-title
        
        youtube-dl https://www.youtube.com/playlist?list=PLrhzvIcii6GNjpARdnO4ueTUAVR9eMBpc --yes-playlist --get-url
        

        【讨论】:

          猜你喜欢
          • 2012-12-06
          • 2019-04-04
          • 2012-05-26
          • 2012-10-24
          • 2017-08-25
          • 2020-06-03
          • 1970-01-01
          • 2014-06-05
          • 2013-02-06
          相关资源
          最近更新 更多