Search code examples
pythonselenium-webdriverxpath

How to click on a button that is inside an iframe


I am attempting to find a robust XPath to click a button in the screenshot below

I want to click on the "Inquiry" button I want to click on the button "Inquiry"

The HTML of the element is made up on the following This is the HTML code for the button

I have tried this code:

driver.find_element(By.XPATH, "/html/body/div/div/div[2]/div[2]/ul/table/tbody/tr/td[2]/li").click

and I am getting this error message:

selenium.common.exceptions.NoSuchElementException: Message: Unable to find element with xpath == /html/body/div/div/div[2]/div[2]/ul/table/tbody/tr/td[2]/li

Solution

  • You need to switch to the frame before accessing the element.You can use below code to switch to the frame:

    wait = WebDriverWait(driver, 20)
    frame = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "frame[name='IDXHeader']")))
    driver.switch_to.frame(frame)
    

    Change locator strategy according based on the attribute available for frame element i.e; By.NAME or By.XPATH or By.ID.

    Since you have ID available for the element. you can directly use ID instead of XPATH. Try below code which will locate Inquiry using ID and clicks on it:

    wait = WebDriverWait(driver, 10)
    inquiry = wait.until(EC.element_to_be_clickable((By.ID, "mn1sub1")))
    inquiry.click()
    
    

    Once you're done accessing element inside frame, switch back to default content using below code:

    driver.switch_to.default_content()
    

    Entire code should be as below:

    wait = WebDriverWait(driver, 20)
    frame = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "frame[name='IDXHeader']")))
    driver.switch_to.frame(frame)
    inquiry = wait.until(EC.element_to_be_clickable((By.ID, "mn1sub1")))
    inquiry.click()
    driver.switch_to.default_content()