【问题标题】:Parsing just first result with beautiful soup用漂亮的汤解析第一个结果
【发布时间】:2019-06-27 00:37:38
【问题描述】:

我有以下代码可以成功提取播客剧集的链接、标题等。我将如何着手拉动它涉及的第一个(即最新一集)然后立即停止并产生那个结果?任何建议将不胜感激。

def get_playable_podcast(soup):
"""
@param: parsed html page            
"""
subjects = []

for content in soup.find_all('item'):

    try:        
        link = content.find('enclosure')
        link = link.get('url')
        print "\n\nLink: ", link

        title = content.find('title')
        title = title.get_text()

        desc = content.find('itunes:subtitle')
        desc = desc.get_text()

        thumbnail = content.find('itunes:image')
        thumbnail = thumbnail.get('href')

    except AttributeError:
        continue

    item = {
            'url': link,
            'title': title,
            'desc': desc,
            'thumbnail': thumbnail
    }

    subjects.append(item) 

return subjects

def compile_playable_podcast(playable_podcast):
"""
@para: list containing dict of key/values pairs for playable podcasts
"""
items = []

for podcast in playable_podcast:
    items.append({
        'label': podcast['title'],
        'thumbnail': podcast['thumbnail'],
        'path': podcast['url'],
        'info': podcast['desc'],
        'is_playable': True,
})

return items

【问题讨论】:

  • 如果您只想要第一个元素,请使用soup.find() 而不是soup.find_all()

标签: python parsing beautifulsoup urllib2


【解决方案1】:

@John Gordon 的回答是完全正确的。
@John Gordon 指出:

soup.find()

将始终显示第一个找到的项目(对你来说这很好,当你想抓取“最新一集”时)。 但是,假设您只想选择 BeautifulSoup 的第二个、第三个、第四个等项。然后您可以使用以下代码行来做到这一点:

soup.find()[0] # This will works the same way as soup.find() and displays the first item

当您将 0 替换为任何其他数字(例如 4)时,您只会得到选择的(在本例中为第四个)项目;)。

【讨论】:

    猜你喜欢
    • 2019-11-10
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    相关资源
    最近更新 更多