How to find the control present in an iframe using selenium? - selenium

I want to find the control present in an iFrame in a webpage using selenium to perform actions like click and setting text in textbox. What is the best way to do that using c# or java language.

By using below code you get controls inside iframe in chrome driver. Install latest selenium chromedriver and place it at C:\chromedriver.exe to below code
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
// Initialize browser
WebDriver driver=new ChromeDriver();
//navigate to url
driver.get("https://demoqa.com/frames");
//Switch to Frame using Index
driver.switchTo().frame(0);
//Identifying the heading in webelement
WebElement frame1Heading= driver.findElement(By.id("sampleHeading"));
//Finding the text of the heading
String frame1Text=frame1Heading.getText();
//Print the heading text
System.out.println(frame1Text);
//closing the driver
driver.close();

Related

Not able to click on a link in a frame

I am not able to click a link in a frame in run mode. First I switched to Frame and then click on a link. After clicking the link, I want to click on another link on the same frame. But not able to click on the second link. In Debug mode, I am able to click both the link.
Used URL: http://demo.guru99.com/selenium/deprecated.html
There are three frames on the page and I switch to frame named "classFrame". On the Frame, I click on the link named "Deprecated". I got all the content of "Deprecated" link. Now I want to click on "Overview" link where I was before. But I am not able to click on link named "Overview". Please help me to click on the second link "Overview".
I am using following code:
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe");
WebDriver driverChrome = new ChromeDriver();
WebDriverWait webWaitVar = new WebDriverWait(driverChrome, 1000);
driverChrome.get("http://demo.guru99.com/selenium/deprecated.html");
driverChrome.switchTo().frame("classFrame");
driverChrome.findElement(By.linkText("Deprecated")).click();
WebElement linkOverview = driverChrome.findElement(By.linkText("Overview"));
webWaitVar.until(ExpectedConditions.visibilityOf(linkOverview));
driverChrome.findElement(By.linkText("Overview")).click();
For page HTML code, Please refer the link as I am not able to paste it here. Thank you very much
To click() on the element with text as Deprecated within the url http://demo.guru99.com/selenium/deprecated.html and again click() on the element with text as Overview, as the the desired element is within a <frame> 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:
cssSelector:
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe");
WebDriver driverChrome = new ChromeDriver();
driverChrome.get("http://demo.guru99.com/selenium/deprecated.html");
new WebDriverWait(driverChrome, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("frame[name='classFrame']")));
new WebDriverWait(driverChrome, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.topNav a[href^='deprecated-list']"))).click();
new WebDriverWait(driverChrome, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("div.topNav a[href^='overview-summary']"))).click();
xpath:
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver.exe");
WebDriver driverChrome = new ChromeDriver();
driverChrome.get("http://demo.guru99.com/selenium/deprecated.html");
new WebDriverWait(driverChrome, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.xpath("//frame[#name='classFrame']")));
new WebDriverWait(driverChrome, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='topNav']//a[starts-with(#href, 'deprecated-list')]"))).click();
new WebDriverWait(driverChrome, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[#class='topNav']//a[starts-with(#href, 'overview-summary')]"))).click();
Here you can find a relevant discussion on Ways to deal with #document under iframe

How to click on save button in chrome print privew page using selenium Java

I am currently looking for a solution to click on Sava button in chrome print preview window with selenium Java.
Is there any way we can handel chrome print preview page?
I have tried with the Robot class, but it seems not reliable/stable for my application.
Could you please someone help me to achieve this with selenium Java.
I fail to see any "Save" button on print preview page for Chrome browser
Here is how you can click "Cancel" button, I believe you will be able to amend the code to match your requirements:
First of all make sure to wait for the preview page to be available using Explicit Wait
Change the context to the print preview window via WebDriver.switchTo() function
All the elements at the print preview page are hidden in ShadowDom therefore you will need to:
Locate the element which is the first parent of the element you're looking for
Get its ShadowRoot property and cast the result to a WebElement
Use the WebElement.findElement() function to locate the next parent
repeat above steps until you reach the desired button
Example code just in case:
new WebDriverWait(driver, 10).until(ExpectedConditions.numberOfWindowsToBe(2));
driver.switchTo().window(driver.getWindowHandles().stream().skip(1).findFirst().get());
WebElement printPreviewApp = driver.findElement(By.tagName("print-preview-app"));
WebElement printPreviewAppConten = expandShadowRoot(printPreviewApp, driver);
WebElement printPreviewSidebar = printPreviewAppConten.findElement(By.tagName("print-preview-sidebar"));
WebElement printPreviewSidebarContent = expandShadowRoot(printPreviewSidebar, driver);
WebElement printPreviewHeader = printPreviewSidebarContent.findElement(By.tagName("print-preview-header"));
WebElement printPreviewHeaderContent = expandShadowRoot(printPreviewHeader, driver);
printPreviewHeaderContent.findElements(By.tagName("paper-button")).get(1).click();
where expandShadowRoot function looks like:
private WebElement expandShadowRoot(WebElement parent, WebDriver driver) {
return (WebElement) ((JavascriptExecutor) driver).executeScript("return arguments[0].shadowRoot", parent);
}
Save button will not work because page is not part of webpage. selenium only support web based application.
But you can use SIKULI to handle above scenario.

Nosuchelementfound exception in Selenium Webdriver

As a new learner for Selenium, I am trying to identify a basic element on the Google page for the Google Search button. However I am getting a NoSuchElementException even though the element is perfectly visible on the page.
Code Snippet :
String driverPath = "C:\\Users\\nchaudhary006\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver",driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
InternetExplorerDriver driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.get("https://google.com");
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
driver.findElement(By.name("btnK"));
Solutions Tried :
Element until visible option
Scroll down so that page is in view
Identifying element by xpath, id , name, etc.
All possible wait combinations.
What can I be possibly doing wrong?
I am not sure to which element you exactly referred by name as btnK but on https://google.com there is a Search field by name as q
Using Selenium 3.4.0, IEDriverServer 3.4.0 & IE 10.x (& above) the below code will put "Neha Chaudhary" in the Search field.
A few words about the Solution:
Once you set ImplicitlyWait at the begining, it remains valid throughout your execution. So you don't have to mention again & again.
Instead of InternetExplorerDriver implementation you must use the WebDriver interface.
While you search for an element driver.findElement(By.name("btnK")); either store it as a WebElement for future use or perform some action by click() or sendKeys("Neha Chaudhary")
Here is the working code snippet:
String driverPath = "C:\\Utility\\BrowserDrivers\\IEDriverServer.exe";
System.setProperty("webdriver.ie.driver",driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
WebDriver driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://google.com");
driver.findElement(By.name("q")).sendKeys("Neha Chaudhary");
Let me know if this Answers your Question.

Popup scroll not working in selenium webdriver

I am running my script in mozilla firefox I want to scroll popup I
applied so many methods but doesn't work for me
I used keys.tab to reach that element but it was unable to enter text in that textfield using senkeys("xyz#gmail.com)
I used scroll method
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("document.getElementById('youama-email').scrollIntoView(true);");
some exception occur
3.I used Moveto element method but got exception
WebElement element = driver.findElement(By.id("youama-email"));
Actions
actions = new Actions(driver);
actions.moveToElement(element);
actions.click();
actions.perform();
// Initialize Javascript executor
JavascriptExecutor js = (JavascriptExecutor) driver;
// Scroll inside web element vertically (e.g. 100 pixel)
js.executeScript("arguments[0].scrollTop =
arguments[1];",driver.findElement(By.id("<div-id>")), 100);
Please help me to scroll and enter into the email as well as other
fields that will appear after scroll [![enter image description
here][1]][1]
[1]: http://i.stack.imgur.com/D0hqI.png
Try this code. I think what you didn't do was to wait for the element to be visible which i did. See the below code. It is running correctly.
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://wyomingvapor.com/");
driver.findElement(By.xpath(".//*[#id='header']/div/div[2]/div/a[1]")).click();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='y-to-register']/input")));
driver.findElement(By.xpath(".//*[#id='y-to-register']/input")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(".//*[#id='youama-firstname']")));
driver.findElement(By.xpath(".//*[#id='youama-firstname']")).sendKeys("xyz#gmail.com");
Thread.sleep(2000L);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_TAB);
robot.keyRelease(KeyEvent.VK_TAB);
robot.keyPress(KeyEvent.VK_X);
robot.keyRelease(KeyEvent.VK_X);
robot.keyPress(KeyEvent.VK_Y);
robot.keyRelease(KeyEvent.VK_Y);
robot.keyPress(KeyEvent.VK_Z);
robot.keyRelease(KeyEvent.VK_Z);
If you still stuck then do reply to me, Jyotsana.
Happy Learning :-)

KeyPress Enter for Selenium

We are doing automation testing and came around with a situation where i need to download the file from the browser .
In Download when the download button is hit we are coming to the system pop for the download where we need to perform the enter operation .
Can some one help us how to perform the enter or keyboard operation currently we are using robot API but it is not working on grid system ,
Here is my code for robot can it be enhanced and used or do we have any alternate way to do it
******** Code *************
public void downloadReportFromMyExport(WebDriver driver, String downloadSufixId) throws AWTException,
InterruptedException
{
String downloadPrefixId = ConfigProperty.getConfig("downloadPrefixId").trim();
String[] suffix;
suffix = StringUtil.split(downloadSufixId, "TR_EXP_");
String suffixPart = suffix[0];
String completeId = downloadPrefixId.concat(suffixPart);
By id = By.id(completeId);
WebElement element = driver.findElement(id);
element.click();
Robot pressKey = new Robot();
pressKey.keyPress(KeyEvent.VK_ENTER);
pressKey.keyRelease(KeyEvent.VK_ENTER);
threadSleep("5");
pressKey.keyPress(KeyEvent.VK_ALT);
pressKey.keyPress(KeyEvent.VK_F4);
pressKey.keyRelease(KeyEvent.VK_F4);
pressKey.keyRelease(KeyEvent.VK_ALT);
logger.info("Downlaod Complete");
}
In firefox browser,
Solution-1
You can change the browser settings so that it saves all downloads to that location without asking.
Refer below link to know to change that setting in firefox.
https://support.mozilla.org/en-US/kb/startup-home-page-download-settings
Solution-2
By using firefox profile setting you can achieve this.
FirefoxProfile profile=new FirefoxProfile();
profile.setPreference("browser.download.folderList",2);
profile.setPreference("browser.download.manager.showWhenStarting",false);
profile.setPreference("browser.download.dir","C:\\Users\\Downloads\\"); profile.setPreference("browser.helperApps.neverAsk.saveToDisk","text/csv");
DesiredCapabilities dc = DesiredCapabilities.firefox();
dc.setCapability(FirefoxDriver.PROFILE, profile);
WebDriver driver=new FirefoxDriver(dc);
yeah i've encountered the same issue
better change the browser settings to save in a particular path
for handling different browsers like,
in FF,
i've used
in firefox by default the control will be on "OPEN" option so..
Robot robot=new Robot();
robot.keyPress(KeyEvent.VK_DOWN);
robot.keyRelease(KeyEvent.VK_DOWN);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
for IE (to save alt+s,to open alt+O) here im saving the file
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_S);
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_S);
for chrome
by default,when ever you click dowload button it will save without showing any popups
and i've succeeded hope it helps you
-Ajay