gpt4 book ai didi

python - BeautifulSoup:抓取嵌入的 href 链接列表

转载 作者:太空宇宙 更新时间:2023-11-03 15:40:37 24 4
gpt4 key购买 nike

我正在这里抓取一些最新热门视频的信息 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'] 匹配的值列表?

最佳答案

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]

对于此类任务,建议使用列表理解

关于python - BeautifulSoup:抓取嵌入的 href 链接列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42173736/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com