2016-04-26 3 views
0

Я работаю с python 2.7. Я хочу, чтобы создать TXT со списком видео в определенном списке YouTube:python- youtube. Получить список видеороликов

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.

Как я могу хранить только ссылки? Есть лучший способ сделать это?

ответ

0

Простой in должен сделать:

for i in href_tags: 
    if 'watch' in str(i): 
     ff.write(str(i)) 
    ff.close() 
0
# 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') 
Смежные вопросы