2017-08-21 187 views
0

我一直在試圖寫一個python腳本,它將獲取我的歌曲名稱中包含的鏈接將被提供的播放列表。例如。 https://www.youtube.com/watch?v=foE1mO2yM04&list=RDGMEMYH9CUrFO7CfLJpaD7UR85wVMfoE1mO2yM04從終端。刮youtube播放列表

我發現使用「li」標籤或「h4」標籤可以提取名稱。 我寫了下面的代碼,

import sys 

link = sys.argv[1] 


from bs4 import BeautifulSoup 
import requests 

req = requests.get(link) 

try: 
    req.raise_for_status() 
except Exception as exc: 
    print('There was a problem:',exc) 

soup = BeautifulSoup(req.text,"html.parser") 

然後我試圖使用鋰標籤作爲:

i=soup.findAll('li') 
print(type(i)) 
for o in i: 
    print(o.get('data-video-title')) 

但它印有「無」的時候那些數字。我相信它無法達到那些包含data-video-title屬性的li標籤。
然後我試圖採用div和H4標記爲,

for i in soup.findAll('div', attrs={'class':'playlist-video-description'}): 
    o = i.find('h4') 
    print(o.text) 

但沒有再次發生..

回答

0

玉傢伙,我已經想通了什麼正在發生。我的代碼是完美的,它的工作正常,問題是我從終端傳遞鏈接作爲參數,並且偶然地,鏈接包含一些符號,這些符號以其他方式被解釋爲例如。 ('&')。 現在我通過鏈接作爲字符串在終端,一切正常。如此愚蠢又費時的錯誤。

0
import requests 
from bs4 import BeautifulSoup 

url = 'https://www.youtube.com/watch?v=foE1mO2yM04&list=RDGMEMYH9CUrFO7CfLJpaD7UR85wVMfoE1mO2yM04' 

data = requests.get(url) 
data = data.text 
soup = BeautifulSoup(data) 

h4 = soup.find_all("h4") 
for h in h4: 
    print(h.text) 

輸出:

 Mike Posner - I Took A Pill In Ibiza (Seeb Remix) (Explicit) 


     Alan Walker - Faded 


     Calvin Harris - This Is What You Came For (Official Video) ft. Rihanna 


     Coldplay - Hymn For The Weekend (Official video) 


     Jonas Blue - Fast Car ft. Dakota 


     Calvin Harris & Disciples - How Deep Is Your Love 


     Galantis - No Money (Official Video) 


     Kungs vs Cookin’ on 3 Burners - This Girl 


     Clean Bandit - Rockabye ft. Sean Paul & Anne-Marie [Official Video] 


     Major Lazer - Light It Up (feat. Nyla & Fuse ODG) [Remix] (Official Lyric Video) 


     Robin Schulz - Sugar (feat. Francesco Yates) (OFFICIAL MUSIC VIDEO) 


     DJ Snake - Middle ft. Bipolar Sunshine 


     Jonas Blue - Perfect Strangers ft. JP Cooper 


     David Guetta ft. Zara Larsson - This One's For You (Music Video) (UEFA EURO 2016™ Official Song) 


     DJ Snake - Let Me Love You ft. Justin Bieber 


     Duke Dumont - Ocean Drive 


     Galantis - Runaway (U & I) (Official Video) 


     Sigala - Sweet Lovin' (Official Video) ft. Bryn Christopher 


     Martin Garrix - Animals (Official Video) 


     David Guetta & Showtek - Bad ft.Vassy (Lyrics Video) 


     DVBBS & Borgeous - TSUNAMI (Original Mix) 


     AronChupa - I'm an Albatraoz | OFFICIAL VIDEO 


     Lilly Wood & The Prick and Robin Schulz - Prayer In C (Robin Schulz Remix) (Official) 


     Kygo - Firestone ft. Conrad Sewell 


     DEAF KEV - Invincible [NCS Release] 


     Eiffel 65 - Blue (KNY Factory Remix) 
+0

感謝您的回覆,但如果您能告訴我我要出錯的地方,這將非常有幫助。 – Shirish