How to Switch to an Element in a Frame Without Using Driver.Switchto().Frame("Framename") in Selenium Webdriver Java

How to identify and switch to the frame in selenium webdriver when frame does not have id

you can use cssSelector,

driver.switchTo().frame(driver.findElement(By.cssSelector("iframe[title='Fill Quote']")));

Selenium - How to send keys within an iFrame?

You don't send character sequence to the <iframe> element rather you would send character sequence to the <input> element within the <iframe>. As the the desired element is within a <iframe> so you have to:

  • Induce WebDriverWait for the desired frameToBeAvailableAndSwitchToIt.

  • Induce WebDriverWait for the desired elementToBeClickable.

  • You can use either of the following Locator Strategies:

  • Using XPATH:

    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='Registration form' and @class='top']")))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@attribure_name='attribute_value']"))).send_keys("Igor Duca")
  • Using CSS_SELECTOR:

    driver.get('https://www.t-online.de/themen/e-mail')
    WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.top[title='Registration form']")))
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[attribure_name='attribute_value']"))).send_keys("Igor Duca")
  • 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

You can find a relevant detailed discussion in How to extract all href from a class in Python Selenium?



References

You can find a couple of relevant discussions in:

  • Ways to deal with #document under iframe
  • Is it possible to switch to an element in a frame without using driver.switchTo().frame(“frameName”) in Selenium Webdriver Java?

Java (Eclipse) - Selenium - xpath - can not identify Web Element

isDisplayed() 

will result in NoSuchElementException if Element is not found. if found it would work expected.

Basically, you'd never be sure if it works or not, cause it is directly dependent on element locator which is not a best practices.

There are two ways to handle this situation

  1. Use findElements instead :

Code :

@FindBy(xpath = "//*[@id='referrals']/tbody/tr[2]/td[2]/div/img[2]") 
private List<WebElement> ChainAndTwoArrowsIcon;

public boolean IconChainWithArrowIsFound() throws InterruptedException {
boolean flag = false;
List<WebElement> elements = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfAllElements(ChainAndTwoArrowsIcon));
if (elements.size()>0) {
System.out.println("Element is visible");
ChainAndTwoArrowsIcon.get(0).getAttribute("title").toString().contains("Associated, and was successfully sent.");
return flag = true;
}
else {
System.out.println("Element is not visible");
return flag;
}
}

Basically, findElements will return a list if element is found, if not then we will have empty list. Based on size of list we have derived the if and else above.


  1. Use try-catch

Code :

@FindBy(xpath = "//*[@id='referrals']/tbody/tr[2]/td[2]/div/img[2]") 
private WebElement ChainAndTwoArrowsIcon;

public boolean IconChainWithArrowIsFound() throws InterruptedException {
try {
return ChainAndTwoArrowsIcon.isDisplayed()
&& ChainAndTwoArrowsIcon.getAttribute("title").toString().contains("Associated, and was successfully sent.");
}
catch (Exception e) {
System.out.println("Something went wrong.");
e.printStackTrace();
return false;
}
}

NoSuchElementException, Selenium unable to locate element

NoSuchElementException

org.openqa.selenium.NoSuchElementException popularly known as NoSuchElementException extends org.openqa.selenium.NotFoundException which is a type of WebDriverException.

NoSuchElementException can be thrown in 2 cases as follows :

  • When using WebDriver.findElement(By by) :

    //example : WebElement my_element = driver.findElement(By.xpath("//my_xpath"));
  • When using WebElement.findElement(By by) :

    //example : WebElement my_element = element.findElement(By.xpath("//my_xpath"));

As per the JavaDocs just like any other WebDriverException, NoSuchElementException should contain the following Constant Fields :

Constant Field      Type                                        Value
SESSION_ID public static final java.lang.String "Session ID"
e.g. (Session info: chrome=63.0.3239.108)

DRIVER_INFO public static final java.lang.String "Driver info"
e.g. (Driver info: chromedriver=2.34.522940 (1a76f96f66e3ca7b8e57d503b4dd3bccfba87af1),platform=Windows NT 6.1.7601 SP1 x86)

BASE_SUPPORT_URL protected static final java.lang.String "http://seleniumhq.org/exceptions/"
e.g. (For documentation on this error, please visit: http://seleniumhq.org/exceptions/no_such_element.html)

Reason

The reason for NoSuchElementException can be either of the following :

  • The Locator Strategy you have adopted doesn't identifies any element in the HTML DOM.
  • The Locator Strategy you have adopted is unable to identify the element as it is not within the browser's Viewport.
  • The Locator Strategy you have adopted identifies the element but is invisible due to presence of the attribute style="display: none;".
  • The Locator Strategy you have adopted doesn't uniquely identifies the desired element in the HTML DOM and currently finds some other hidden / invisible element.
  • The WebElement you are trying to locate is within an <iframe> tag.
  • The WebDriver instance is looking out for the WebElement even before the element is present/visibile within the HTML DOM.

Solution

The solution to address NoSuchElementException can be either of the following :

  • Adopt a Locator Strategy which uniquely identifies the desired WebElement. You can take help of the Developer Tools (Ctrl+Shift+I or F12) and use Element Inspector.

    Here you will find a detailed discussion on how to inspect element in selenium3.6 as firebug is not an option any more for FF 56?

  • Use executeScript() method to scroll the element in to view as follows :

    WebElement elem = driver.findElement(By.xpath("element_xpath"));
    ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();", elem);

    Here you will find a detailed discussion on Scrolling to top of the page in Python using Selenium

  • Incase element is having the attribute style="display: none;", remove the attribute through executeScript() method as follows :

    WebElement element = driver.findElement(By.xpath("element_xpath"));
    ((JavascriptExecutor)driver).executeScript("arguments[0].removeAttribute('style')", element)
    element.sendKeys("text_to_send");
  • To check if the element is within an <iframe> traverse up the HTML to locate the respective <iframe> tag and switchTo() the desired iframe through either of the following methods :

    driver.switchTo().frame("frame_name");
    driver.switchTo().frame("frame_id");
    driver.switchTo().frame(1); // 1 represents frame index

    Here you can find a detailed discussion on Is it possible to switch to an element in a frame without using driver.switchTo().frame(“frameName”) in Selenium Webdriver Java?.

  • If the element is not present/visible in the HTML DOM immediately, induce WebDriverWait with ExpectedConditions set to proper method as follows :

    • To wait for presenceOfElementLocated :

      new WebDriverWait(driver, 20).until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='buttonStyle']//input[@id='originTextField']")));
    • To wait for visibilityOfElementLocated :

      new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='buttonStyle']//input[@id='originTextField']")));
    • To wait for elementToBeClickable :

      new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@class='buttonStyle']//input[@id='originTextField']")));

Reference

You can find Selenium's python client based relevant discussion in:

  • Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome


Related Topics



Leave a reply



Submit