Selenium - move page to front - selenium

I am performing a web page scrape and update using Selenium and phantomJS webdriver. At one stage, completing one page can bring up either page_A or page_B. The page I want is page_B. If page_A appears, I can locate the elements:
<li class="menu_item">
<a class="menu_item_anchor_selected" href="#page_a">Page_A</a>
</li>
<li class="menu_item">
<a class="menu_item_anchor" href="#page_b">Page_B</a>
</li>
and I can then extract the target from the anchor to page_B. However, once loaded by the driver, every element on page_B remains invisible.
public class fill_page_B (WebDriver driver, String target) throws Exception
{
String currentUrl = driver.getCurrentUrl;
String page_B_Url = currentUrl + target;
driver.get (page_B_Url);
// prove that page_B actually loaded
String page = driver.getPageSource ();
System.println (page);
WebElement we = driver.findElement (By.id ("MyId"));
// ignore test for we exists; it does
WebDriver wait = new WebDriverWait (driver, 60); // should be long enough!
wait.until (ExpectedConditions.visibilityOf (we)); // fails
. . .
}
I have tried using:
driver.manage().window().maximize();
and other tricks to ensure the window hasn't shrunk to make the required control outside the viewable window and other, similar tricks to make sure it hasn't migrated off the screen entirely.
I have also tried:
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript ("arguments[0].checked=true;", we);
to force the element to be visible. This approach however merely threw an Exception "cannot click on option element. Executing JavaScript click function returned an unexpected error etc."
However, when I ran my application again, this time using an Internet Explorer driver, I noticed that when I got page_B (and proved it by displaying the page contents in the system log), page_A was still visible. I did try resizing page_A (which was previously maximized) before getting page_B, but this made no difference; everything on page_B remained invisible and unclickable.
Any suggestions as to how Selenium could deal with this?

Related

Selenium couldn't find an element inside the iframe

I am creating an automated test cases for this page https://cloud.google.com/products/calculator in scope of my practical task using Selenium + Java.
At some point I've faced with a problem when the WebDriver couldn't find an element inside the iframe, even if in the previous test case I was able to interact with the elements of this iframe.
All my test cases are running one by one without closing the driver and each next test case can passed only if the previous test case passed as well.
Here is my GitHub repo:
https://github.com/SerhiiVeselov/hurt-me-planty.git
Here are my test cases:
#BeforeAll
public static void driverSetup() {
driver = new ChromeDriver();
driver.manage().window().maximize();
mainPage = new MainPage(driver);
searchResultsPage = new SearchResultsPage(driver);
pricingCalculatorPage = new PricingCalculatorPage(driver);
fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(10))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
}
#Test
#Order(1)
#DisplayName("Search of the Pricing Calculator page")
public void openPricingCalculator() {
mainPage.openPage();
fluentWait.until(ExpectedConditions.visibilityOf(mainPage.getCookiesOkBtn()));
mainPage.closeCookiesPopUp();
mainPage.openSearchField();
mainPage.enterSearchRequest();
fluentWait.until(ExpectedConditions.visibilityOf(mainPage.getSuggestSearchResult()));
mainPage.clickSuggestSearchResult();
fluentWait.until(ExpectedConditions.visibilityOf(searchResultsPage.getSearchResultsTab()));
searchResultsPage.clickPricingCalculatorLink();
assertEquals("https://cloud.google.com/products/calculator", driver.getCurrentUrl());
fluentWait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(pricingCalculatorPage.getCloudSideFrame()));
fluentWait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt((pricingCalculatorPage.getMyFrame())));
}
#Test
#Order(2)
#DisplayName("Fill the Calculation Form")
public void fillCalculationForm() {
pricingCalculatorPage.enterNumberOfInstances();
pricingCalculatorPage.selectOperatingSystem();
pricingCalculatorPage.selectProvisioningModel();
pricingCalculatorPage.selectMachineType();
pricingCalculatorPage.checkAddGpuCheckBox();
pricingCalculatorPage.selectGpuType();
pricingCalculatorPage.selectGpuQuantity();
pricingCalculatorPage.selectLocalSsd();
pricingCalculatorPage.selectDatacenterLocation();
pricingCalculatorPage.addToEstimate();
fluentWait.until(ExpectedConditions.visibilityOf(pricingCalculatorPage.getTotalEstimatedCost()));
assertEquals("Instance type: n1-standard-8", pricingCalculatorPage.getInstanceTypeTest().getText());
}
#Test
#Order(3)
#DisplayName("Check the name of the Machine type")
public void verifyMachineType() {
assertEquals("Instance type: n1-standard-8", pricingCalculatorPage.getInstanceTypeTest().getText());
}
Here is the webpage for which I've created 2d and 3d test cases: https://cloud.google.com/products/calculator
page for automation in 2d and 3d test cases
So far, 1st and 2d test cases are passing and working as expected. But 3d test case is failing all the time cause the WebDriver couldn't find the element from the getInstanceTypeTest method:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[contains(text(), 'Instance type')]"}
Most of elements I interested in are located inside the same iframe (id=myFrame).
I have a selector for instanceTypeTest WebElement creared using xpath //div[contains(text(), 'Instance type')].
In 3d test case I want to check this field and get from it a text value to compare it with the value which was selected at the left form at https://cloud.google.com/products/calculator page.
I guess, after I filling the left form with data and clicking the 'ADD TO ESTIMATE' button something is happening with the iframes or the driver is loosing it's focus to the right frame.
I tried to add at the beginning of the 3d test case some code which should take driver back to the default web page content and then switch driver to outer iframe (cloudSideFrame) and after that - to inner iframe (myFrame):
driver.switchTo().defaultContent(); fluentWait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(pricingCalculatorPage.getCloudSideFrame())); fluentWait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt((pricingCalculatorPage.getMyFrame())));
It didn't help me. Driver still couldn't find Instance type field.
I can't understand why driver could find some elements inside the iframe even if it could find some others inside the same iframe.
Please help me to solve this problem.

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.

Selenium Web Driver

We are working on IE Automation using Selenium Web driver in C#.Net.
We are getting an exception in handling model popup window. We supposed to do below the action.
When we click on Link button it will open a popup window then we need switch to popup window selecting check box options and click on Submit button.
When clicking on Link button we are able to open the popup window. But here we are facing an issue like the child popup window is not loading with data and getting HTTP 500 Internal server Error.
I don't understand sometimes it was working properly with the same code but not all the times I am getting above issue when I am trying to perform above actions on child window.
is this any IE settings issue or my code issue even i ignored protected mode settings in IE settings.
I am trying with below code :
js.ExecuteScript("arguments[0].click();", driver.FindElement(By.XPath("//*[#id='ByNewNotes']")));
(or)
string jsWindowString = "NewWindow('pop_Type.jsp?Type=External&IuserId=NUVJK50'," + sessionId + ",'400','500');return false";
((IJavaScriptExecutor)driver).ExecuteScript(jsWindowString);
Could you please help on this issue.
Thanks in Advance.
Instead of using ExpectedConditions.ElementEx‌​ists use ExpectedConditions.elementToBeClickable or presenceOfElementLocated
WebDriverWait wait = new WebDriverWait(driver, 60);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(""//*[‌​#id='ByNewNotes']")));
element.click();
Either Try to use FluentWait. Create a by function of your element which you want to wait and pass it in below method
WebElement waitsss(WebDriver driver, By elementIdentifier){
Wait<WebDriver> wait =
new FluentWait<WebDriver>(driver).withTimeout(60, TimeUnit.SECONDS) .pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);
return wait.until(new Function<WebDriver, WebElement>()
{
public WebElement apply(WebDriver driver) {
return driver.findElement(elementIdentifier);
}});
}
Hope it will help you :)
Have you tried
Thread.Sleep(2000);
We had the same issues and solved it with this simple way.

Selenium Chrome webdriver can't find elements after content is reloaded

I'm testing a page where the div reloads with a form that has multiple textboxesand buttons. However after the div is reloaded the webdriver can't find any of the elements on the screen. I've tried different waits but it never finds the elements. However, when I try to find an element that didn't change (i.e. a top nav element) it finds it fine.
Driver.Instance.FindElement(By.Id("igtxttxt_CAge")).Click();
var wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(10));
wait.Until(d => d.SwitchTo().ActiveElement().GetAttribute("id") == "igtxttxt_CAge");
Is there something I can do for when the div content is refreshed?
Error received:
no such element: Unable to locate element:
{"method":"id","selector":"igtxttxt_CAge"}
(Session info: chrome=56.0.2924.76)
(Driver info: chromedriver=2.27.440174
I found the answer to this question. I didn't realize until I looked at the HTML content that the Driver contained that the page I was loading was loaded in an iFrame.
Once I added this code:
Driver.Instance.SwitchTo().Frame("frame_Calculator");
Then the rest of my code worked as expected:
Driver.Instance.FindElement(By.Id("igtxttxt_CAge")).Click();
((IJavaScriptExecutor)Driver.Instance).ExecuteScript("$('#igtxttxt_CAge').trigger('focus')");
In your given scenario, I think fluentwait is better candidate than webdriverwait. You can try the following code. It will ignore all such no element not found exceptions while the webdriver waits.
FluentWait fluentWait = new FluentWait<>(webDriver) {
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(200, TimeUnit.MILLISECONDS);
.ignoring(NoSuchElementException.class, TimeoutException.class)
.ignoring(StaleElementReferenceException.class);
}
And the you can use it until your element is clickable or visible.
fluentWait.until(ExpectedConditions.visibilityOf(By.Id("igtxttxt_CAge")));
fluentWait.until(ExpectedConditions.elementToBeClickable(By.Id("igtxttxt_CAge")));
Hope this will help. here is a difference between webdriverwait and fluentwait.

How to locate elements on a javascript form using Selenium WebDriver

I have a page that renders a login form. Using Firefox's firebug I have identified the username id = txtUsername and the password text box is txtPassword. Everything is fine in Firefox. BUT moving over to IE Explorer browser, am getting error and cant locate the elements.
On inspecting the page, I found the form is being rendered by a JavaScript function. Below is the html:
form name="frmLogin" id="frmLogin" onsubmit="return $('#frmLogon').valid();" action="default.aspx" method="post" jQuery172043="1" novalidate="novalidate"
How can I locate the page elements using selenium webdriver.
This is the code I have written.
/* setup for IE. Remove if not needed */
File file = new File("C:/SeleniumJavaLibrary/selenium-2.28.0/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
caps.setCapability("ignoreZoomSetting", true);
WebDriver driver = new InternetExplorerDriver(caps);
driver.manage().timeouts().implicitlyWait(28,TimeUnit.SECONDS );
/*setup for IE*/
driver.get("http://website.com");
WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('#frmLogin').valid();");
element.findElement(By.name("txtUsername")).sendKeys("user");
element.findElement(By.name("txtPassword")).sendKeys("password");
I would do the following:
WebDriverWait waiting = new WebDriverWait(driver, 15, 100);
WebElement element = waiting.until(ExpectedConditions.visibilityOfElementLocated(By.id("frmLogin")));
This will create a WebDriverWait object that will wait up to 15 seconds, checking to see if the expected condition is valid every 100 milliseconds. This object is then used to wait until the frmLogin element is visible on the page, and then returns you a WebElement that can be used later on in your test (if required).