我想写一个代码,将从我喜欢的视频喜欢起飞。我尝试了两个请求。第一个是我要找出视频的id,第二个是执行删除。我想把这个变成一个循环,但我有麻烦,只有一个视频了。这是我第一次使用api,所以我肯定我做错了什么。
import os
import pickle
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
credentials = None
# token.pickle stores the user's credentials from previously successful logins
if os.path.exists('token.pickle'):
print('Loading Credentials From File...')
with open('token.pickle', 'rb') as token:
credentials = pickle.load(token)
# If there are no valid credentials available, then either refresh the token or log in.
if not credentials or not credentials.valid:
if credentials and credentials.expired and credentials.refresh_token:
print('Refreshing Access Token...')
credentials.refresh(Request())
else:
print('Fetching New Tokens...')
flow = InstalledAppFlow.from_client_secrets_file('client_secret.json',
scopes=["https://www.googleapis.com/auth/youtube.readonly",
"https://www.googleapis.com/auth/youtube",
"https://www.googleapis.com/auth/youtube.force-ssl"])
flow.run_local_server(port=8080, prompt='consent', authorization_prompt_message='')
credentials = flow.credentials
# Save the credentials for the next run
with open('token.pickle', 'wb') as f:
print('Saving Credentials for Future Use...')
pickle.dump(credentials, f)
youtube = build("youtube", "v3", credentials=credentials)
request = youtube.videos().list(part="snippet,contentDetails,statistics", myRating="like", maxResults=1).execute()
#print(request)
# Getting title, id and duration of liked video
for item in request["items"]:
global vid_title
global vid_id
global vid_time
vid_title = item["snippet"]["title"]
vid_id = item["id"]
vid_time = item["contentDetails"]["duration"]
vid_time = vid_time.replace("M", " minute ")
vid_time = vid_time.replace("S", " second ")
vid_time = vid_time[2:]
# print(vid_title)
#print(vid_id)
request = youtube.videos().rate(id=vid_id, rating="none").execute()
print(vid_title + " was removed from the liked videos")
我想把这个变成for循环,但是我也只有一个视频有问题
我想应该是这句话:
request = youtube.videos().rate(id=vid_id, rating="none").execute()
这一行应该在for
循环内.
仔细检查代码的缩进
修改后的代码:
# Getting title, id and duration of liked video:
for item in request["items"]:
global vid_title
global vid_id
global vid_time
vid_title = item["snippet"]["title"]
vid_id = item["id"]
vid_time = item["contentDetails"]["duration"]
vid_time = vid_time.replace("M", " minute ")
vid_time = vid_time.replace("S", " second ")
vid_time = vid_time[2:]
# Remove the rate of the video:
request = youtube.videos().rate(id=vid_id, rating="none").execute()
# Print the video's title
print(vid_title + " was removed from the liked videos")