unable to click on webelement with selenium ActionsChain or javascript click as it refreshes the page and gives StaleElementReferenceError

I’m trying to close a cookie consent pop-up on a site https://www.meinschiff.com/. I used selenium webdriver for chrome to find the close and accept div element and click on whichever is found first. If I manually choose deny button, then it is closed but it hangs with a loading of another layer. The element’s parent’s parent div element with id=”blur” acts as an ever loading overlay. The code fetches the accept button first and clicks on it but it refreshes the page giving StaleElementReference error. The clicks work perfectly when I open the site in a normal chrome browser.
I want to click accept button and close the pop up.

My code:

          div_elements = WebDriverWait(driver, 
         5).until(EC.presence_of_all_elements_located((By.TAG_NAME, "div")))
     for div_element in div_elements:
        try:
            element_html = div_element.get_attribute("outerHTML")
            div_element_attrs = BeautifulSoup(element_html, "lxml").div.attrs
            # class_attr = div_element.get_attribute('class')
            # title_attr = div_element.get_attribute('title')
            value_attr = div_element.get_attribute('value')
            popup_div = False
            for key in div_element_attrs.keys():
                if any(keyword in (div_element.get_attribute(key) or '').lower() 
                     for keyword in close_keywords) or 
                    (value_attr is not None and value_attr.lower() == 'false'):
                    print("closing div pop-up...")
                    popup_div = True
                    break
                else:
                    if any(keyword in (div_element.get_attribute(key) or 
                        '').lower() for keyword in accept_keywords) or 
                        (value_attr is not None and value_attr.lower() == 'false'):
                        print("accepting div pop-up...")
                        popup_div = True
                        break
            if popup_div: 
                ActionChains(driver).move_to_element(div_element).click().perform()
                time.sleep(2)
                if div_element.is_displayed():
                    print("div element not closed")
                    return False
                else:
                    print("div element closed")
                    return True
        except ElementClickInterceptedException:
             print(f"Div Element click intercepted: 
             {div_element.get_attribute('outerHTML')}")
            continue
        except Exception as e:
             print(f"Error processing div element: {e}")
            continue

I have also tried javascript click with:

driver.execute_script("arguments[0].scrollIntoView(true);", div_element)
driver.execute_script("arguments[0].click();", div_element)

and wait for element to be clickable and it results in same behavior:

 clickable_element = WebDriverWait(driver, 
           10).until(EC.element_to_be_clickable(div_element)) 
      ActionChains(driver).move_to_element(clickable_element).click().perform()

3

I don’t know if i have truly understand your post but like @browsermator say’s, it seem’s to be a timing issue.

You can use Implicit Waits : Selenium-python Documentation

5.2. Implicit Waits An implicit wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element (or
elements) not immediately available. The default setting is 0 (zero).
Once set, the implicit wait is set for the life of the WebDriver
object.

from selenium import webdriver

driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds
driver.get("http://somedomain/url_that_delays_loading")
myDynamicElement = driver.find_element_by_id("myDynamicElement")

The script below launch the driver, set an implicit waits of 10 seconds, go to meinschiff webpage , deny cookie and print the slogan of meinschiff :

from selenium import webdriver
from selenium.webdriver.common.by import By

# Create a new instance of the Chrome driver
driver = webdriver.Chrome()
driver.implicitly_wait(10) 

# Open the website
driver.get('https://www.meinschiff.com/')

try:
    # Close and refuse cookies
    driver.find_element(By.ID, "privacy_pref_optout").click()
    
    # Print the slogan in the webpage 
    slogan = driver.find_element(By.ID, "html")
    print(slogan.text)
    
except Exception as e:
    print(e)

I hope it will help you. Feel free to tell us if your issu is solved.

1

Solution:
I have set allow cookies to True in the selenium chrome options prefs settings and now the button is clickable and closes the popup. I’m still getting StaleElementReferenceError because the page gets refreshed and found element is erased from the driver.

 chrome_options.add_experimental_option("prefs", {
        "profile.default_content_setting_values.cookies": 1})

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật