John Stepehns
John Stepehns

Reputation: 27

Cant locate iframe by contains in xPath

Trying to access this iframe but cannot seem to target it. While using xpath I have to use contain as the iframe id is always changing the last numbers.

<iframe id="cardinal-stepUpIframe-1659117883889" src="about:blank" frameborder="0" name="cardinal-stepUpIframe-1659117883889"></iframe>

I currently have the following code to try and access the iframe. I have tried accessing it via //* which does not seem to work either.

newiframe = WebDriverWait(driver,20).until(EC.presence_of_element_located((By.XPATH,"//iframe[contains(@id, 'cardinal-stepUpIframe')]")))
driver.switch_to.frame(newiframe)
print('switched to frame')

Any help would be great, thanks.

Upvotes: 1

Views: 152

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193058

To switch to the <iframe> instead of presence_of_element_located() you have to induce WebDriverWait for the desired frame to be available and switch to it and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR and id attribute:

    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[id^='cardinal-stepUpIframe']")))
    
  • Using XPATH and name attribute:

    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[starts-with(@name, 'cardinal-stepUpIframe')]")))
    
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

Upvotes: 1

Related Questions