0

I want to make a program that shows a channel's subscriber count. My code works fine and gives me the correct subscriber count when the id of the channel has not been customized, but when the id has been customized, the json result does not contain an "items" tag.

Non-customized id:

{
  "kind": "youtube#channelListResponse",
  "etag": "18WUxifrtT73p-fgWEjP_ReiVQs",
  "pageInfo": {
    "totalResults": 1,
    "resultsPerPage": 5
  },
  "items": [
    {
      "kind": "youtube#channel",
      "etag": "r7AcY54fWu7t_3lHv3W5KQjgns0",
      "id": "UC8butISFwT-Wl7EV0hUK0BQ",
      "statistics": {
        "viewCount": "268031518",
        "subscriberCount": "4660000",
        "hiddenSubscriberCount": false,
        "videoCount": "1236"
      }
    }
  ]
}

Customized id:

{
  "kind": "youtube#channelListResponse",
  "etag": "RuuXzTIr0OoDqI4S0RU6n4FqKEM",
  "pageInfo": {
    "totalResults": 0,
    "resultsPerPage": 5
  }
}

My code:

import urllib.request
import json


def grab_id(id):
    data = urllib.request.urlopen(f"https://www.googleapis.com/youtube/v3/channels?part=statistics&id={id}&key=mykey").read()
    subs = json.loads(data)["items"][0]["statistics"]["subscriberCount"]
    subs = int(subs)
    return subs


print(grab_id("id"))

Thanks!

Charo
  • 15
  • 6
  • Okay, and what is your *question* about this result? – Karl Knechtel Dec 07 '21 at 02:26
  • @KarlKnechtel There is no items tag, so I cannot get the subscriber count – Charo Dec 07 '21 at 02:27
  • I don't think the distinguishing feature here is really whether " the id has been customized". I think the distinguishing feature is the number of `"totalResults"` in the `"pageInfo"`. – Karl Knechtel Dec 07 '21 at 02:27
  • Ah, so then your question is simply "how do I get the subscriber count for a channel with the youtube API?" and if you simply [try using a search engine in an obvious way](https://duckduckgo.com/?q=youtube+api+channel+subscriber+count), you can easily find references for that, including a [previous Stack Overflow question](https://stackoverflow.com/questions/30723866/youtube-subscriber-count-with-youtube-data-api-v3). – Karl Knechtel Dec 07 '21 at 02:29
  • @KarlKnechtel I visited the question and found that the code is almost identical to mine. – Charo Dec 07 '21 at 02:32
  • If you are looking for a way to retrieve the real channel id beginning with "UC" in a way which works more than using [Search: list](https://developers.google.com/youtube/v3/docs/search/list) which isn't very stable from my experience, you can `curl https://youtube.com/c/BenjaminLoison/` (modify BenjaminLoison with the customized channel name) and take the first channel id coming (as I said it starts with "UC") – Benjamin Loison Dec 07 '21 at 13:00

0 Answers0