[Python] Unable to interact with elements inside iframe on a dynamic site

Discussão em 'Python' iniciado por Stack, Setembro 25, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to automate a dynamic site: https://erp.pgu.ac.ir/Dashboard. This site contains iframes and dynamic elements (generated by JavaScript) that I need to interact with. My target element is inside an iframe, and I am switching to the iframe before trying to interact with the element. However, I keep encountering a NoSuchElementException.

    Here's the error:

    selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":".first-part-1 .mat-grid-tile:nth-child(2) span"}



    Here is the HTML structure I'm working with:

    <iframe src="...">
    <div class="mat-grid-tile-content">
    <div class="first-part-1">
    <div class="mat-grid-tile">
    <span>Clickable Element</span>
    </div>
    </div>
    </div>
    </iframe>



    I have used Selenium IDE to record the steps and generated the following Python code:

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

    class TestTest():
    def setup_method(self, method):
    options = webdriver.ChromeOptions()
    options.add_experimental_option("detach", True)
    self.driver = webdriver.Chrome(options=options)

    def teardown_method(self, method):
    self.driver.quit()

    def test_test(self):
    self.driver.get("https://erp.pgu.ac.ir/Dashboard")
    time.sleep(10)
    self.driver.set_window_size(1552, 832)
    time.sleep(10)

    # Switch to iframe
    self.driver.switch_to.frame(1)
    time.sleep(10)

    # Attempt to click the element inside iframe
    self.driver.find_element(By.CSS_SELECTOR, ".first-part-1 .mat-grid-tile:nth-child(2) span").click()

    testClass = TestTest()
    testClass.setup_method("")
    testClass.test_test()
    testClass.teardown_method("")



    I have ensured that I am switching to the iframe using switch_to.frame(1). I’ve tried waiting for the iframe to load by adding time.sleep(10). I am using the correct CSS selector, which works when manually inspecting the page. Despite this, I still get a NoSuchElementException error. I would expect Selenium to find and click the element, but it seems it can't locate it.

    Continue reading...

Compartilhe esta Página