【问题标题】:How to get data for channel url without id or username?如何在没有 id 或用户名的情况下获取频道 url 的数据?
【发布时间】:2019-04-13 20:57:27
【问题描述】:

我偶然发现了 YouTube 网址 https://www.youtube.com/u2。它导致一个频道页面。当我点击频道的视频,然后点击视频的频道链接时,我会回到同一页面,但网址为 https://www.youtube.com/channel/UC4gPNusMDwx2Xm-YI35AkCA

但是如何使用 YouTube 数据 API 从 https://www.youtube.com/u2 转到 https://www.youtube.com/channel/UC4gPNusMDwx2Xm-YI35AkCA?通道的 API 参考没有记录执行此操作的方法。我可以搜索类型为频道的 u2,这会给我频道 ID,但它也会给我其他频道 ID。对于频道,似乎没有将https://www.youtube.com/u2 列为替代网址的数据。

【问题讨论】:

    标签: youtube youtube-api youtube-data-api


    【解决方案1】:

    如果无法通过 API 获取频道 ID(我不确定),那么应该下载站点(等等。使用 curl 或您的编程语言发出 HTTP 请求的首选方式)和解析它。指向实际频道页面的链接多次包含在 HTML 源代码中(在 <head> 中),您可以从这段摘录中看到:

    <link rel="canonical" href="https://www.youtube.com/channel/UC4gPNusMDwx2Xm-YI35AkCA">
    
    <meta property="og:site_name" content="YouTube">
    <meta property="og:url" content="https://www.youtube.com/channel/UC4gPNusMDwx2Xm-YI35AkCA">
    <meta property="og:title" content="U2">
    <meta property="og:description" content="Rock band from Dublin, Ireland. Adam Clayton on Bass. The Edge on Guitar. Larry Mullen Jr on Drums. Bono on Vocals. http://www.u2.com">
    

    即使您不想完全解析网站并提取标题信息,使用 &lt;link rel="canonical" href="https:\/\/www\.youtube\.com\/channel\/(.+)"&gt; 进行正则表达式搜索也可能会奏效,但请注意,这并不能保证 100% 有效。

    【讨论】:

    • 谢谢。这很好用,使用 jsoup (jsoup.org) 只需几行代码。所以,我的问题现在已经解决了,我赞成你的答案,但我不愿意将其标记为正确答案,因为这是一个非官方的解决方案,将来可能会在不通知的情况下被破坏。
    • 我希望我能找到另一种方法,而不是使用正则表达式。
    【解决方案2】:

    我不知道我发布问题时是否没有找到它,或者它是否是新问题,但现在 YouTube 数据 API 具有用于频道的 snippet.customUrl,在给定示例中为 "u2"。所以你可以这样做:

    // Kotlin
    
    fun getChannelById(id: String): Channel? =
        youTube.channels().list("id, snippet")
            .setKey(apiKey)
            .setId(id)
            .execute()
            .items
            ?.single()
    
    private fun getChannelByCustomUrl(customUrl: String): Channel? =
        youTube.search().list("id, snippet")
            .setKey(apiKey)
            .setType("channel")
            .setQ(customUrl)
            // .setMaxResults(5) // The default value 5 should suffice.
            .execute()
            .items
            ?.asSequence()
            ?.mapNotNull {
                // Can be null when channel has been deleted just after search().
                this.getChannelById(it.snippet.channelId)
            }
            ?.firstOrNull { it.snippet.customUrl == customUrl }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多