Certainly! I can help you develop two programs to achieve your goal:
-
Web Scraping Program: This program will scrape the NCS Fandom wiki category page, extract the track names and corresponding YouTube links from each page, and save them into a text file.
-
YouTube Playlist Creator: This program will read the list of YouTube video IDs from the text file and create a YouTube playlist with those videos.
Before we proceed, please ensure that you comply with the terms of service of the websites involved (NCS Fandom Wiki and YouTube) and that you have the necessary permissions to perform these actions.
Part 1: Web Scraping Program
Overview
We'll use Python with the requests and BeautifulSoup libraries to scrape the NCS Fandom wiki.
Prerequisites
-
Python 3.x installed on your system.
-
Install required libraries:
pip install requests beautifulsoup4
Code
import requests
from bs4 import BeautifulSoup
import time
def scrape_category_page(category_url):
page_number = 1
tracks = []
while True:
print(f"Processing page {page_number}...")
response = requests.get(f"{category_url}?page={page_number}")
soup = BeautifulSoup(response.content, 'html.parser')
# Find all track links on the page
track_links = soup.select('.category-page__member-link')
if not track_links:
break # No more tracks
for link in track_links:
track_name = link.get_text()
track_url = f"https://nocopyrightsounds.fandom.com{link['href']}"
youtube_link = extract_youtube_link(track_url)
if youtube_link:
tracks.append((track_name, youtube_link))
else:
print(f"No YouTube link found for {track_name}")
time.sleep(1) # Be polite and don't hammer the server
page_number += 1
return tracks
def extract_youtube_link(track_url):
response = requests.get(track_url)
soup = BeautifulSoup(response.content, 'html.parser')
# Look for YouTube iframe or external link
iframe = soup.find('iframe', {'src': lambda x: x and 'youtube.com' in x})
if iframe:
youtube_url = iframe['src']
# Clean up the URL if necessary
youtube_url = youtube_url.split('?')[0]
return youtube_url
# Alternatively, look for a direct link
for link in soup.find_all('a', href=True):
if 'youtube.com' in link['href']:
return link['href']
return None
def save_tracks_to_file(tracks, filename):
with open(filename, 'w', encoding='utf-8') as f:
for track_name, youtube_link in tracks:
f.write(f"{track_name}\t{youtube_link}\n")
def main():
category_url = input("Enter the category URL: ").strip()
playlist_name = category_url.split("Category:")[-1].replace("_", " ")
output_filename = f"{playlist_name} Tracks.txt"
tracks = scrape_category_page(category_url)
save_tracks_to_file(tracks, output_filename)
print(f"Scraped {len(tracks)} tracks.")
print(f"Track list saved to '{output_filename}'.")
if __name__ == "__main__":
main()
Explanation
- scrape_category_page: Navigates through the category pages, extracts track names and their page URLs.
- extract_youtube_link: Visits each track's page and tries to find the YouTube link.
- save_tracks_to_file: Saves the track names and YouTube links to a text file, separated by a tab (
\t).
- main: Orchestrates the process.
Usage
-
Run the script:
python scrape_ncs_tracks.py
-
When prompted, enter the category URL (e.g., https://nocopyrightsounds.fandom.com/wiki/Category:Melodic_Dubstep_music).
-
The script will generate a text file named Melodic Dubstep music Tracks.txt with the track names and YouTube links.
Part 2: YouTube Playlist Creator
Overview
We'll use the YouTube Data API to create a playlist and add videos to it.
Prerequisites
- Google Account with a YouTube channel.
- YouTube Data API v3 enabled in Google Developers Console.
- API Credentials (API key, OAuth 2.0 client ID, and client secret).
- Python libraries:
google-auth-oauthlib, google-api-python-client.
Setup
-
Enable YouTube Data API v3:
- Go to the Google Developers Console.
- Create a new project or select an existing one.
- Enable the YouTube Data API v3 for your project.
-
Create OAuth Credentials:
- Go to Credentials.
- Click Create Credentials > OAuth client ID.
- Choose Desktop app.
- Download the
credentials.json file.
-
Install Required Libraries:
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
Code
import os
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
SCOPES = ["https://www.googleapis.com/auth/youtube"]
def get_authenticated_service():
client_secrets_file = "credentials.json"
# Get credentials and create an API client
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
client_secrets_file, SCOPES)
credentials = flow.run_console()
youtube = googleapiclient.discovery.build(
"youtube", "v3", credentials=credentials)
return youtube
def create_playlist(youtube, playlist_title, playlist_description=""):
request = youtube.playlists().insert(
part="snippet,status",
body={
"snippet": {
"title": playlist_title,
"description": playlist_description
},
"status": {
"privacyStatus": "public"
}
}
)
response = request.execute()
return response["id"]
def add_video_to_playlist(youtube, playlist_id, video_id):
request = youtube.playlistItems().insert(
part="snippet",
body={
"snippet": {
"playlistId": playlist_id,
"resourceId": {
"kind": "youtube#video",
"videoId": video_id
}
}
}
)
response = request.execute()
return response
def main():
youtube = get_authenticated_service()
input_filename = input("Enter the name of the track list file: ").strip()
playlist_title = input("Enter the name of the playlist to create: ").strip()
# Create a new playlist
playlist_id = create_playlist(youtube, playlist_title)
print(f"Created playlist '{playlist_title}' with ID: {playlist_id}")
# Read video IDs from the file and add them to the playlist
with open(input_filename, 'r', encoding='utf-8') as f:
for line in f:
track_name, youtube_link = line.strip().split('\t')
# Extract video ID from the YouTube link
if "v=" in youtube_link:
video_id = youtube_link.split("v=")[-1]
elif "youtu.be/" in youtube_link:
video_id = youtube_link.split("youtu.be/")[-1]
else:
print(f"Could not extract video ID from {youtube_link}")
continue
# Remove any additional URL parameters
video_id = video_id.split('&')[0]
try:
add_video_to_playlist(youtube, playlist_id, video_id)
print(f"Added '{track_name}' to playlist.")
except Exception as e:
print(f"Failed to add '{track_name}': {e}")
if __name__ == "__main__":
main()
Explanation
- get_authenticated_service: Authenticates with the YouTube Data API using OAuth 2.0.
- create_playlist: Creates a new YouTube playlist with the given title.
- add_video_to_playlist: Adds a video to the specified playlist.
- main: Reads the track list file, extracts video IDs, and adds them to the playlist.
Usage
-
Place the credentials.json file in the same directory as your script.
-
Run the script:
python create_youtube_playlist.py
-
When prompted:
- Enter the name of the track list file generated from the first program (e.g.,
Melodic Dubstep music Tracks.txt).
- Enter the desired playlist name (e.g.,
NCS - Melodic Dubstep).
-
Follow the authentication flow in the console window to grant access to your YouTube account.
-
The script will create the playlist and add all the videos.
Notes
-
Adjustments for Missing Links: Before running the second program, you can open the text file and manually edit or remove any entries with missing or incorrect YouTube links.
-
Multiple Genres: You can reuse these scripts for other genres by changing the category URL and playlist name accordingly.
-
Rate Limits: Be mindful of YouTube's API quotas and rate limits. Avoid making excessive requests in a short period.
-
Error Handling: The scripts include basic error handling. You may want to enhance it to handle specific exceptions and retry logic.
-
Compliance: Always ensure that you comply with the terms of service of the platforms involved. Obtain necessary permissions if required.
I hope this helps you achieve your goal! Let me know if you have any questions or need further assistance.