使用 selenium 关闭 javascript 弹出窗口

问题描述 投票:0回答:1

我正在使用 selenium 编写一个小型 python 示例,以从我居住的地区的 hemnet 网站获取信息。当我使用 selenium 打开页面时,会出现一个弹出窗口,但我尚未找到使用驱动程序访问代码以关闭弹出窗口的方法。这是我迄今为止尝试过但没有成功的方法:

def close_all_popups(driver):
    driver.window_handles
    for h in driver.window_handles:
        driver.switch_to_window(h)
        driver.close()
    driver.switch_to_window(driver.window_handles[0])

try:
    options = Options()
    options.add_argument("--incognito")
    options.add_argument("--window-size=1920x1080")

    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=options)

    driver.get("https://www.hemnet.se")

    wait = WebDriverWait(driver, 10)

    driver.switch_to.window(driver.window_handles[-1])

    body = driver.find_elements(By.TAG_NAME, "body")

    popup = driver.find_elements(By.ID, "uc-center-container")

    # body.send_keys(Keys.TAB)

    close_all_popups(driver)

    driver.execute_script("window.onbeforeunload = function(e){};")

    alert = Alert(driver)

    # alert.accept()

    # alert.dismiss()

    # frame = driver.find_elements(By.XPATH,"//iframe[.//a[contains(@id, 'uc-center-container')]]")
    # driver.switchTo.frame(frame)

    popup_element = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.CSS_SELECTOR, "sc-ddjGPC jinACp"))
    )
    popup = driver.find_elements(By.ID, "uc-center-container")
    # alert = driver.switch_to.alert

    buttons = driver.find_elements(By.CLASS_NAME, "sc-dcJsrY kIAuBW")

    wait = WebDriverWait(driver, 10)
    popup = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".uc-banner-content")))
    wait = WebDriverWait(driver, timeout=2)

    popup_html = popup.get_attribute('innerHTML')
    print(popup_html)

    alert = wait.until(lambda d: d.switch_to.alert)
    text = alert.text
    alert.accept()

    wait = WebDriverWait(driver, 10)
    popup = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".uc-banner-content")))

    accept_button = driver.find_element(By.CSS_SELECTOR, ".uc-buttons > button:nth-child(2)")
    accept_button.click()

    def accept_cookies():
        buttons = driver.find_elements(By.TAG_NAME, "button")
        for button in buttons:
            if button.text == 'Acceptera alla':
                button.click()
                return True
        return False

    timeout = 30
    start_time = time.time()
    while time.time() - start_time < timeout:
        if accept_cookies():
            print("Clicked 'Acceptera alla' button.")
            break
        time.sleep(1)  # Wait for 1 second before checking again
    else:
        print("Timeout: 'Acceptera alla' button not found.")

    print("done")

finally:
    driver.quit()

如果有人能给我一些解决方案,我将不胜感激!

javascript python selenium-webdriver
1个回答
0
投票

假设您指的是cookie弹窗,下面是解决方案。

如果您注意到 HTML,目标元素位于 shadow-root 元素内。检查下面的代码来处理它。

代码:

import time
from selenium import webdriver

driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.hemnet.se/")
# Access the shadow root using JavaScript and click it
cookie_btn = driver.execute_script("""return document.querySelector('div#usercentrics-root').shadowRoot.querySelector('button.sc-dcJsrY.kIAuBW')""")
cookie_btn.click()
time.sleep(10)

参考:https://stackoverflow.com/a/78152794/7598774

© www.soinside.com 2019 - 2024. All rights reserved.