1

So, I'm trying to create a Script that opens a Google Chrome page and search "LMFAO", for example. Only a problem: Cookies. I want to learn how to delete a specific element from a webpage, in this case the Cookies Pop-up of youtube.

Here's the actual script.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time

driver = webdriver.Chrome()
driver.get('https://youtube.com')

time.sleep(8)

driver.execute_script("""
   const ll = document.getElementById("dialog")[0];
   ll.remove();
""")

searchbox = driver.find_elements_by_xpath('//*[@id="search"]')
searchbox.send_keys('LMFAO')

Cookie Popup snapshot:

Here

For the undetected Selenium Comment, here's the button html:

<tp-yt-paper-button id="button" class="style-scope ytd-button-renderer style-primary size-default" role="button" tabindex="0" animated="" elevation="0" aria-disabled="false" aria-label="Agree to the use of cookies and other data for the purposes described"><!--css-build:shady--><yt-formatted-string id="text" class="style-scope ytd-button-renderer style-primary size-default">I Agree</yt-formatted-string><paper-ripple class="style-scope tp-yt-paper-button"><!--css-build:shady-->
    

    <div id="background" class="style-scope paper-ripple"></div>
    <div id="waves" class="style-scope paper-ripple"></div>
</paper-ripple></tp-yt-paper-button>

1 Answers1

1

You don't have to delete the cookie consent popup and can simply click on I AGREE.


To click on the element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "tp-yt-paper-button[aria-label='Agree to the use of cookies and other data for the purposes described'] yt-formatted-string.style-scope.ytd-button-renderer.style-primary.size-default#text"))).click()
    
  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//tp-yt-paper-button[@aria-label='Agree to the use of cookies and other data for the purposes described']//yt-formatted-string[@class='style-scope ytd-button-renderer style-primary size-default' and text()='I Agree']"))).click()
    
  • Note: You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352