我有一个脚本,可以使用 Youtube 的 API 获取信息并将其保存到 Excel 文件中。
脚本对于某些频道正常运行,而对于某些频道则不能正常运行,例如当我在 BBC 和 CNN 频道上使用它时,它获得了所需的所有信息,但当我在 MrBeast 或 Tech With Tim 频道上尝试时,它只返回了 3 个关于 MrBeast 的视频和 2 个关于 Tech With Tim 的视频,尽管两者都频道有更多视频。
可能是什么问题?
这是完整的代码:
import pandas as pd
from googleapiclient.discovery import build
api_key = 'YOUR_API_KEY_HERE' # Replace with your API key
youtube = build('youtube', 'v3', developerKey=api_key)
# Retrieve the channel ID for the given username
channel_request = youtube.channels().list(
part='snippet,contentDetails',
forUsername='BBCNews'
)
channel_response = channel_request.execute()
# Extract channel username and ID
channel_username = channel_response['items'][0]['snippet']['title']
channel_id = channel_response['items'][0]['id']
# Initialize variables for pagination
next_page_token = None
all_videos = []
# Retrieve all videos from the channel
while True:
videos_request = youtube.search().list(
part='snippet',
channelId=channel_id,
type='video',
order='date',
maxResults=50, # Maximum results per page
pageToken=next_page_token
)
videos_response = videos_request.execute()
all_videos.extend(videos_response['items'])
next_page_token = videos_response.get('nextPageToken')
if not next_page_token:
break # Break the loop if there are no more pages
# Initialize lists to store extracted information
titles = []
published_dates = []
likes = []
views = []
descriptions = []
urls = []
# Extract information from each video
for video in all_videos:
video_id = video['id']['videoId']
video_title = video['snippet']['title']
video_description = video['snippet']['description']
video_published_at = video['snippet']['publishedAt']
video_url = f'https://www.youtube.com/watch?v={video_id}'
# Retrieve statistics for each video
video_statistics_request = youtube.videos().list(
part='statistics',
id=video_id
)
video_statistics_response = video_statistics_request.execute()
video_statistics = video_statistics_response['items'][0]['statistics']
video_likes = int(video_statistics.get('likeCount', 0))
video_views = int(video_statistics.get('viewCount', 0))
# Append extracted information to lists
titles.append(video_title)
published_dates.append(video_published_at)
likes.append(video_likes)
views.append(video_views)
descriptions.append(video_description)
urls.append(video_url)
# Create a DataFrame from the lists
data = {
'Title': titles,
'Published Date': published_dates,
'Likes': likes,
'Views': views,
'Description': descriptions,
'URL': urls
}
df = pd.DataFrame(data)
# Save DataFrame to Excel file with channel username as filename
excel_file_path = f'{channel_username}_videos.xlsx'
df.to_excel(excel_file_path, index=False)
print("Excel file saved successfully.")
(刚刚在 Upwork 上看到您的提案,并已发送提案以获得这份工作,因为这将是我的第一份工作,但还是让我在这里分享解决方案)
您可以尝试获取频道 id,因为 youtube 除了用户名之外还有每个频道的频道 id/url,但由于用户名而被隐藏。
您可以尝试以下函数来获取频道ID:
def get_channel_id(identifier):
if re.match(r'^[a-zA-Z0-9_-]{24}$', identifier):
return identifier
else:
channel_request = youtube.channels().list(
part='snippet,contentDetails',
forUsername=identifier
)
channel_response = channel_request.execute()
return channel_response['items'][0]['id']
channel_identifier = 'Channel_Name'
channel_id = get_channel_id(channel_identifier)
PS:如果您的问题得到解决,请接受我的建议,这最终会帮助我获得更多客户:D