Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions yt-skip-ads.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
'''python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, ElementClickInterceptedException, StaleElementReferenceException
import time
from selenium.webdriver.chrome.options import Options

# --- Standard setup (ensure chromedriver is in PATH or specify executable_path) ---
options = Options()
options.binary_location = "/usr/bin/chromium" # Adjust this path to your Chromium binary
driver = webdriver.Chrome(options=options)
# --- End Standard setup ---

driver.get("https://www.youtube.com")
print("Successfully opened YouTube.")
print("Please navigate to a video or let a video with an ad play.")
print("The script will monitor for and attempt to skip ads.")

SKIP_BUTTON_LOCATORS = [
(By.CLASS_NAME, "ytp-ad-skip-button-modern"),
(By.CLASS_NAME, "ytp-ad-skip-button"),
(By.XPATH, "//button[.//div[contains(@class,'ytp-ad-text') and normalize-space()='Skip']]"),
(By.XPATH, "//button[.//span[contains(text(),'Skip')]]"),
(By.CSS_SELECTOR, ".videoAdUiSkipButton,.ytp-ad-skip-button-modern,.ytp-ad-skip-button")
]

WAIT_TIMEOUT = 3

try:
while True:
for strategy, locator_value in SKIP_BUTTON_LOCATORS:
try:
skip_button = WebDriverWait(driver, WAIT_TIMEOUT).until(
EC.element_to_be_clickable((strategy, locator_value))
)
if skip_button.is_displayed() and skip_button.is_enabled():
print(f"Skip Ad button found with {strategy}: {locator_value}. Attempting to click...")
try:
driver.execute_script("arguments[0].click();", skip_button)
print("Ad skipped!")
time.sleep(2) # Wait a bit after skipping
break
except ElementClickInterceptedException:
print(f"Button click intercepted for {strategy}: {locator_value}. Trying JavaScript click again or waiting.")
try:
driver.execute_script("arguments[0].click();", skip_button)
print("Ad skipped via JS after interception!")
time.sleep(2)

break
except Exception as e_js:
print(f"JS click also failed after interception: {e_js}")
except TimeoutException:
continue
except StaleElementReferenceException:
print(f"Stale element reference for {strategy}: {locator_value}. The page might have changed. Retrying.")
break
except Exception as e:
print(f"An unexpected error occurred while trying locator {strategy} {locator_value}: {e}")
time.sleep(1)

except KeyboardInterrupt:
print("Script stopped by user.")
except Exception as e:
print(f"An unhandled error occurred in the main loop: {e}")
finally:
print("Closing the browser...")
driver.quit()
Loading