【问题标题】:How to get data for channel url without id or username?如何在没有 id 或用户名的情况下获取频道 url 的数据?
【发布时间】:2019-04-13 20:57:27
【问题描述】:
【问题讨论】:
标签:
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">
即使您不想完全解析网站并提取标题信息,使用 <link rel="canonical" href="https:\/\/www\.youtube\.com\/channel\/(.+)"> 进行正则表达式搜索也可能会奏效,但请注意,这并不能保证 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 }