I'm trying to accept cookies with Selenium, but the accept button is not found. I am not familiar with Selenium and I don't know how to debug. For instance, if I try to accept cookies from stackoverflow.com.
This is my code:
driver = webdriver.Chrome("chromedriver")
driver.get("https://stackoverflow.com")
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'flex--item')]/div[text()='Accept all cookies']"))).click()
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "flex--item s-btn s-btn__filled js-cookie-settings"))).click()
Whatever the selected option (Xpath or CSS), the button is not found. How can I debug my Xpath or CSS selector ? What is the solution ?
CodePudding user response:
To click()
on the element Accept all cookies' you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
Using XPATH and
normalize-space()
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[normalize-space()='Accept all cookies']"))).click()
Using XPATH and
contains()
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(., 'Accept all cookies')]"))).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