BeautifulSoup: 抓取嵌入的 href 链接列表
BeautifulSoup: Scrape list of embedded href links
我正在这里 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 多个),我收到一个错误此方法的数据类型 returns.
for v in videos:
videos[v].div.a['href']
>> TypeError: list indices must be integers, not Tag
如何 运行 通过 'videos' 中返回的 div 列表并打印出匹配 'video[n].[=22= 的值列表]['href'] ?
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]
使用列表理解 推荐用于此类任务
我正在这里 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 多个),我收到一个错误此方法的数据类型 returns.
for v in videos:
videos[v].div.a['href']
>> TypeError: list indices must be integers, not Tag
如何 运行 通过 'videos' 中返回的 div 列表并打印出匹配 'video[n].[=22= 的值列表]['href'] ?
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]
使用列表理解 推荐用于此类任务