【发布时间】:2017-02-11 08:10:29
【问题描述】:
我正在收集有关https://www.youtube.com/feed/trending 的一些最新热门视频的信息。我将页面加载到 BeautifulSoup 中,但在尝试运行需要解析的 div 列表时出错。
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
到目前为止,我已经返回了我需要的信息,但是当我尝试遍历所有 div 时(截至撰写本文时,此页面上已超过 70 个),我收到与此方法返回的数据类型相关的错误。
for v in videos:
videos[v].div.a['href']
>> TypeError: list indices must be integers, not Tag
如何遍历 'videos' 中返回的 div 列表并打印出与 'video[n].div.a['href'] 匹配的值列表?
【问题讨论】:
标签: python html web-scraping beautifulsoup urllib2