[Python] Locating an iframe in a closed shadow root

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I am making a program that bypasses the cloudflare "Verify that you are human" check using Python, Selenium (and some javascript). The problem is that the checkbox element is located in a closed shadow root that's located in an iframe, that's located in a closed shadow root. The structure can be seen here by inspecting the checkbox.

    So far, I managed to get into the first (outer) shadow root but cannot access the iframe in it.

    This is my code:

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

    driver = webdriver.Chrome()

    # Inject script to force shadow DOMs open
    driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {'source': """
    Element.prototype._attachShadow = Element.prototype.attachShadow;
    Element.prototype.attachShadow = function () {
    return this._attachShadow( { mode: "open" } );
    };
    """})

    # open the site
    driver.get("https://annas-archive.org/slow_download/c9cc2ebc974bb1955881807bdca7807d/0/0")

    # wait for the page to load properly
    sleep(3)

    # Access the outer shadow DOM
    outer_shadow_host = driver.find_element(By.CSS_SELECTOR, '#JStsl2 > div > div')
    outer_shadow_root = driver.execute_script('return arguments[0].shadowRoot', outer_shadow_host)

    # locate the iframe
    iframe = outer_shadow_root.find_element(By.CSS_SELECTOR, "#cf-chl-widget-xn7qb")

    # Switch to the iframe
    driver.switch_to.frame(iframe)

    # Access the inner shadow DOM
    inner_shadow_host = outer_shadow_root.find_element(By.CSS_SELECTOR, 'body')
    inner_shadow_root = driver.execute_script('return arguments[0].shadowRoot', inner_shadow_host)

    # Find and interact with the target element inside the inner shadow root
    target_element = inner_shadow_root.find_element(By.XPATH, '//input[type="checkbox"]')
    target_element.click()


    To locate the iframe element I have tried:

    • Using By.TAG_NAME and By.XPATH
    • Making the element visible with the following line of code: driver.execute_script("arguments[0].style.display='block'; arguments[0].style.visibility='visible';", iframe)

    Continue reading...

Compartilhe esta Página