【问题标题】:BeautifulSoup: Scrape list of embedded href linksBeautifulSoup:嵌入href链接的抓取列表
【发布时间】: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


    【解决方案1】:
    for v in range(len(videos)):
         videos[v].div.a['href']
    

    您需要的是videos list 的索引,而不是其中的标签。

    更好:

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

    好多了:

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

    建议使用列表理解来完成此类任务

    【讨论】:

    • 谢谢!列表理解格式有效,但第一个没有。错误:“TypeError:'int' 对象不可迭代”
    猜你喜欢
    • 1970-01-01
    • 2017-05-29
    • 2019-03-05
    • 2015-03-08
    • 2021-03-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 2022-10-22
    相关资源
    最近更新 更多