@sxrx

В чем ошибка кода Python Request?

import requests
import hashlib
import re
import time


class YouTube(object):
    base_headers = {
       'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36',
    }
    origin = 'https://studio.youtube.com'
    referer = f'{origin}/channel/0/monetization'

    def __init__(self, cookies: dict):
        self.__CHANNEL_ID = None
        self.__API_KEY = None
        self.__SAPISIDHASH = None

        self.cookies = cookies
        self.session = requests.Session()
        self.session.headers.update(self.base_headers)
        self.load_cookies()

    def load_cookies(self) -> None:
        for key, value in self.cookies.items():
            self.session.cookies.set(key, value)

    def set_data(self) -> None:
        response = self.session.get(self.referer)
        self.__CHANNEL_ID = re.findall(r"channelId\":\"(.*?)\"", response.text)[0].strip()
        self.__API_KEY = re.findall(r"innertubeApiKey\":\"(.*?)\"", response.text)[0].strip()
        hash_authorization = hashlib.sha1(
            ' '.join([str(int(time.time())), self.cookies['__Secure-1PAPISID'], self.origin]).encode()).hexdigest()
        self.__SAPISIDHASH = str(int(time.time())) + '_' + hash_authorization

    def get_data_of_monetization(self) -> dict:
        headers = {
            'authorization': f'SAPISIDHASH {self.__SAPISIDHASH}',
            'origin': self.origin,
            'referer': self.origin + f'/channel/{self.__CHANNEL_ID}/monetization',
        }

        params = {"context": {
            "client": {"clientName": 62, "clientVersion": "1.20220518.02.00", "hl": "ru", "gl": "BY",
                       "experimentsToken": "",
                       "utcOffsetMinutes": 180, "screenWidthPoints": 1880, "screenHeightPoints": 374,
                       "screenPixelDensity": 1,
                       "screenDensityFloat": 1, "userInterfaceTheme": "USER_INTERFACE_THEME_DARK"}},
            "channelIds": [self.__CHANNEL_ID],
            "mask": {"features": {"all": False},
                     "channelUiCustomization": {"all": False},
                     "permissions": {"overallPermissions": False},
                     "channelId": True,
                     "monetizationStatus": True,
                     "monetizationDetails": {"all": True},
                     "contentOwnerAssociation": {"all": False},
                     "settings": {"coreSettings": {"featureCountry": False, "country": True},
                                  "copyright": {"copyrightAgreementStatus": False}, "studio": {"all": True}},
                     "contracts": {"all": False},
                     "title": True,
                     "thumbnailDetails": {"all": False},
                     "isPartner": True,
                     "metric": {"all": False},
                     "timeCreatedSeconds": False,
                     "isMonetized": True,
                     "isOfficialArtistChannel": True,
                     "isNameVerified": True,
                     "sponsorships": {"all": False},
                     "selfCertification": {"all": False},
                     "channelVisibility": False,
                     "interstitials": {"all": False},
                     "monetizationStatusData": {"all": True}}}

        response = self.session.post(
            f'https://studio.youtube.com/youtubei/v1/creator/get_creator_channels?alt=json&key={self.__API_KEY}',
            json=params, headers=headers)
        return response.json()

    @property
    def get_channel_id(self) -> str:
        return self.__CHANNEL_ID

    @property
    def get_api_key(self) -> str:
        return self.__API_KEY

    @property
    def get_sapisidhash(self) -> str:
        return self.__SAPISIDHASH


if __name__ == '__main__':
    cookie = {'__Secure-1PSID': '',
              '__Secure-1PAPISID': ''
              }

    client = YouTube(cookie)
    client.set_data()
    response = client.get_data_of_monetization()


Мне выводит что выходит за индех но я не понимаю почему
self.__CHANNEL_ID = re.findall(r"channelId\":\"(.*?)\"", response.text)[0].strip()
IndexError: list index out of range
  • Вопрос задан
  • 89 просмотров
Пригласить эксперта
Ответы на вопрос 1
freeExec
@freeExec
Участник OpenStreetMap
re.findall(r"channelId\":\"(.*?)\"", response.text)[0].strip()

Вроде бы очевидно, что вы обращаетесь к элементу которого нет.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы