【问题标题】:I have trouble webscraping the channels tab of a YouTube channel using python我无法使用 python 抓取 YouTube 频道的频道选项卡
【发布时间】:2021-04-09 02:44:23
【问题描述】:

我正在尝试抓取此 YouTube 频道的频道标签:https://www.youtube.com/c/mkbhd/channels

我的目标是提取提到的频道的名称(在下图中突出显示):

这就是我的好样子:

import requests
from bs4 import BeautifulSoup


r = requests.get('https://www.youtube.com/c/mkbhd/channels')
html_content = r.text

soup = BeautifulSoup(html_content)
print(soup.prettify())

阅读太长而无法在此处发布的输出时,我无法在频道选项卡中看到单个频道的名称。我想知道频道名称是否是动态加载的,因此我无法像通常在静态网站上那样抓取它。你有解决这个问题的办法吗?

print(soup.find_all('a'))

我还尝试查找所有<a> 标签,以便在页面中找到频道网址,但这也没有成功。它有效,但没有一个链接可以潜在地引用频道网址。

【问题讨论】:

    标签: python web-scraping youtube


    【解决方案1】:

    在我看来,最好的方法是解析 HTML 中的 JSON,而不是使用 BeautiulSoup。

    import requests, json
    
    
    r = requests.get('https://www.youtube.com/c/mkbhd/channels')
    html_content = r.text
    
    content = json.loads((html_content.split('var ytInitialData = ')[1].split(';')[0]))
    
    for item in content["contents"]["twoColumnBrowseResultsRenderer"]["tabs"][4]["tabRenderer"]["content"]["sectionListRenderer"]["contents"][0]["itemSectionRenderer"]["contents"][0]["gridRenderer"]["items"]:
        print(item["gridChannelRenderer"]["title"]["simpleText"])
    

    这不是最漂亮的,但效果很好。

    输出

    20syl
    Madeon
    Jonathan Morrison
    Brandon Havard
    Vinh Dang
    Austin Evans
    Unbox Therapy
    UrAvgConsumer
    

    【讨论】:

    • 谢谢它确实有效,但你知道更清洁的方法吗?
    • @Nassims 很高兴听到它有效,如果您认为这是您选择的答案,您可以勾选绿色复选标记。我认为个人不会有更清洁的方式,我会使用它。根据我的经验,JSON 比 BeautifulSoup 更可取。
    猜你喜欢
    • 2022-11-07
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2014-05-02
    • 2018-10-19
    • 2014-06-28
    • 2020-05-22
    • 1970-01-01
    相关资源
    最近更新 更多