在使用 Python 脚本将视频上传到 YouTube 频道时,若希望将视频上传到第二个频道,需要解决 OAuth2 授权的问题。
解决方案:
- 创建新的 Google Cloud 项目:
from google.oauth2 import service_account
import googleapiclient.discovery
def create_new_project():
credentials = service_account.Credentials.from_service_account_file(
http://www.jshk.com.cn/mb/reg.asp?kefu=xiaoding;//爬虫IP免费获取;
'service_account.json')
service = googleapiclient.discovery.build(
'cloudresourcemanager', 'v1', credentials=credentials)
body = {
'projectId': 'your-new-project-id'
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/2cc5083e7f0448d8b0434ec0395071be.png)
new_project = service.projects().create(body=body).execute()
print('New project created: {}'.format(new_project['projectId']))
create_new_project()
- 为新项目启用 YouTube Data API:
from google.oauth2 import service_account
import googleapiclient.discovery
def enable_youtube_api():
credentials = service_account.Credentials.from_service_account_file(
'service_account.json')
service = googleapiclient.discovery.build(
'cloudresourcemanager', 'v1', credentials=credentials)
project_id = 'your-new-project-id'
body = {
'serviceIds': ['youtube.googleapis.com']
}
service.projects().enableServices(projectId=project_id, body=body).execute()
print('YouTube Data API enabled for project: {}'.format(project_id))
enable_youtube_api()
- 为新项目创建 OAuth2 凭据:
from google.oauth2 import service_account
import googleapiclient.discovery
def create_oauth2_credentials():
credentials = service_account.Credentials.from_service_account_file(
'service_account.json')
service = googleapiclient.discovery.build(
'iam', 'v1', credentials=credentials)
project_id = 'your-new-project-id'
body = {
'serviceAccount': 'service-account-name@your-new-project-id.iam.gserviceaccount.com'
}
credentials = service.projects().serviceAccounts().keys().create(
name='projects/-/serviceAccounts/' + body['serviceAccount'],
body=body).execute()
print('OAuth2 credentials created for service account: {}'.format(credentials['name']))
create_oauth2_credentials()
- 使用新项目和创建的 OAuth2 凭据上传视频:
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
def upload_video():
# OAuth2 flow for the new project
flow = InstalledAppFlow.from_client_secrets_file('client_secrets.json', ['https://www.googleapis.com/auth/youtube.upload'])
credentials = flow.run_console()
youtube = build('youtube', 'v3', credentials=credentials)
# Upload the video
video_metadata = {
'snippet': {
'title': 'My Video',
'description': 'This is a test video',
'tags': ['test', 'video']
},
'status': {
'privacyStatus': 'private'
}
}
video_data = open('video.mp4', 'rb').read()
response = youtube.videos().insert(
part='snippet,status',
body=video_metadata,
media_body=video_data).execute()
print('Video uploaded: {}'.format(response['id']))
upload_video()