'How to accept facebook cookies using python selenium?

I have a problem clicking the facebook accept cookies button on facebook creator studio website. Cookies are shown only when the page is opened by the program, not when you open it manually.

Here is my code:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome('C:\\Users\\kocia\\OneDrive\\Plocha\\Python\\nastaveni\\chromedriver.exe')
driver.maximize_window()
driver.get('https://business.facebook.com/creatorstudio/?tab=instagram_content_posts')

Here is what i tried:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Přijmout vše']"))).click()

or

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="u_0_6_k1"]'))).click()

I found out, that for some reason the id changes every time.

Thank you for your help



Solution 1:[1]

You are right, the id changes randomly every time, but I found a workaround. Look at this snippet:

driver.find_elements_by_xpath("//button[contains(string(), 'Allow essential and optional cookies')]")[0].click()

I use this xpath: "//button[contains(string(), 'Allow essential and optional cookies')]" it search for a button that contains the string "Allow essential and optional cookies". In the main login page there is only one button that has this feature so I get the first element in the returned list [0] then it clicks it click().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 badr