2017-02-11 1 views
1

가장 최근의 인기 급상승 동영상에 대한 정보를 여기에서 모으고 있습니다. https://www.youtube.com/feed/trending. 내가 페이지를 BeautifulSoup에로드했지만 구문 분석이 필요한 div 목록을 실행할 때 오류가 발생합니다.BeautifulSoup : 임베디드 href 링크 스크랩 목록

import urllib2 
from bs4 import BeautifulSoup 

url = 'https://www.youtube.com/feed/trending' 
page = urllib2.urlopen(url) 
soup = BeautifulSoup(page,'html.parser') 

#narrow in to divs with relevant meta-data 
videos = soup.find_all('div',class_='yt-lockup-content') 
videos[50].div.a['href'] #checking one specific DIV 
>>u'user/nameofchannel' #works 

는 지금까지 내가 필요한 정보를 돌아왔다,하지만 난 (글을 쓰는이 페이지에 70 +)를 모든 div를 통해 실행하려고하면,이 메서드가 반환하는 데이터 유형과 관련된 오류 .

for v in videos: 
    videos[v].div.a['href'] 
>> TypeError: list indices must be integers, not Tag 

어떻게 '비디오'반환 것 사업부의 목록을 실행하고 일치하는 값의 목록을 인쇄 할 수 있습니다 '비디오 [N] .div.a ['HREF ']?

답변

1
for v in range(len(videos)): 
    videos[v].div.a['href'] 

필요한 항목은 videos 목록의 색인이지 태그가 아닙니다.

더 나은 :

for index, value in enumerate(videos): 
    videos[index].div.a['href'] 

훨씬 더 :

[v.div.a['href'] for v in videos] 

사용 지능형리스트이 작업의 이런 종류의

+0

감사하는 것이 좋습니다! 목록 이해 형식이 효과가 있었지만 처음에는 이해하지 못했습니다. 오류 : "TypeError : 'int'객체를 반복 할 수 없습니다." – James