I'm unable to click on a button (Application built on Angular Js). My automation framework is existing one built on Java/Selenium WebDriver. I have tried with Xpath, CSS, etc still not working.
<button type="button" id="Button2" class="btn btn-primary btn-xs" data-ng-click="StartWizard()" data-ng-keyup="$event.keyCode == 13 ? StartWizard() : null">Import New File</button>
Script:
WebElement clickNextButton = driver.findElement(By.xpath("//button[contains(text(),'Import New File')]"));
clickNextButton.click();
Error:
Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//button[contains(text(),'Import New File')]"}
Could you please help me to resolve this. Please let me know if this can be resolved using ngWebDriver?
You can execute the ng-click function defined in the element:
String waitForAngularJs = "angular.element(\"#Button2\").scope().StartWizard();";
try {
ExpectedCondition<Boolean> waitForAngular = new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeAsyncScript(waitForAngularJs).equals(true);
}
};
WebDriverWait wait = new WebDriverWait(myWebDriver, 60);
wait.until(waitForAngular);
}catch(Exception e) {
e.printStackTrace();
}
Enjoy the code!
Related
HTML:
<input name="txtAnswer" type="text" maxlength="20" id="txtAnswer" class="box1">
Code trials:
driver.findElement(By.xpath("//table[#id='tblSecurityAnswer']//tbody//tr[2]//td[2]//input[#id='txtAnswer']")).sendKeys("green");
and also:
driver.findElement(By.cssSelector("//tr:nth-child(1) > td > table > tbody >
// tr:nth-child(2) > td:nth-child(2)"));
public static void main(String[] args) throws InterruptedException {
WebDriver driver;
// IE webdriver
// System.setProperty("webdriver.ie.driver", "C:\\IEDriverServer.exe");
// driver = new InternetExplorerDriver();
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver = new ChromeDriver();
// Maximize the browser window
driver.manage().window().maximize();
// navigate to specified url
driver.get("http://dxbqcapp01/molforms/login.aspx");
driver.findElement(By.id("txtUserName")).sendKeys("MS200963915");
driver.findElement(By.id("txtPassword")).sendKeys("test#123");
driver.findElement(By.xpath("//input[#type='submit' and #value='Submit']")).sendKeys(Keys.ENTER);
driver.findElement(By.id("txtAnswer")).sendKeys("green");
The error stack trace would have helped us to debug your issue in a better way. However to send a character sequence to the desired element you have to induce WebDriverWait for the element to be clickable and you can use either of the following Locator Strategies:
cssSelector:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.box1#txtAnswer"))).sendKeys("green");
xpath:
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#class='box1' and #id='txtAnswer']"))).sendKeys("green");
In my scenario, when I launch a URL, an authentication alert window opens up and I need to enter Username and Password from excel and on clicking on 'Log In' it'll show me the web homepage. I've implemented this using the below code snippet and it's working perfectly in IE11. But when I'm trying to run the same code in Chrome v60, it's not working. It's showing the authentication alert window but not performing any action on it. Screenshot attached. Can anyone suggest please.
Selenium WD version - 3.4.0
Code:
public static void loadApplicationURL(WebDriver driver) throws Exception
{
String SSPathl = null;
String URL = Generic_Functions.GetParameterFromInputSheet("URL");
try
{
driver.get(URL);
Thread.sleep(6000);
LoginApplication.isAlertPresent(driver);
}
}
public static boolean isAlertPresent(WebDriver driver) {
try {
driver.switchTo().alert();
UserAndPassword UP = new UserAndPassword(UserName,Password);
driver.switchTo().alert().authenticateUsing(UP);
Thread.sleep(8000);
return true;
}
catch (Exception e) {
return false;
}
}
For test browsers, have created a separate class. Find below the snippet used for IE and Chrome browsers.
For Chrome
System.setProperty("webdriver.chrome.driver",".\\Resources\\chromedriver.exe");
driver = new ChromeDriver()
In case of IE,
[System.setProperty("webdriver.ie.driver",".\\Resources\\IEDriverServer.exe");
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
ieCapabilities.setCapability("nativeEvents", true);
driver = new InternetExplorerDriver(ieCapabilities);][1]
So here's the thing. I have a popup that has a button, the button itself has a fileDownloadActionListener, this one is responsible for downloading an excel file. So what I need basically is to hide the popup right after I generate the file.
Here's my .jspx file (Just the popup)
<af:popup childCreation="deferred" autoCancel="enabled"
id="myPopUp"
contentDelivery="lazyUncached"
binding="#{viewScope.mbMyBean.myPopUp}"
partialTriggers="b17">
<af:dialog id="d16" type="cancel"
title="Do you wish to download a file?"
inlineStyle="width:400px;">
<af:panelGroupLayout id="pgl32"
inlineStyle="max-width: 200px;">
<af:outputText value="You're about to download a file. Ready?" id="ot45"
/>
</af:panelGroupLayout>
<f:facet name="buttonBar">
<af:button text="GO" id="b17"
<af:fileDownloadActionListener contentType="excelHTML"
filename="#{viewScope.mbMyBean.FileName}"
method="#{viewScope.mbMyBean.GenerateEmptyExcel}"
/>
</af:button>
</f:facet>
</af:dialog>
</af:popup>
And here's the java method:
public void GenerateEmptyExcel(FacesContext facesContext, OutputStream outputStream) {
try {
HSSFWorkbook wb1 = generateEmptyExcelFile();
wb1.write(outputStream);
outputStream.flush();
outputStream.close();
this.myPopUp.hide();
AdfFacesContext.getCurrentInstance().addPartialTarget(this.myPopUp);
System.gc();
} catch (Exception e) {
e.printStackTrace();
}
}
PROBLEM
The popup won't hide.
NOTES
The popup is properly binded within the bean
I do not own this code and I'm doing a maintainance.
I do not know why the programmer used System.gc() since I consider it as a bad practice. Here's a good reason
I had the same problem after downloading a file, you should try this:
Use a resource type javascript to trigger an event click in commandButton
<af:resource type="javascript">
function customHandler(evt) {
console.log(evt);
var exportCmd = AdfPage.PAGE.findComponentByAbsoluteId("pt1:b17");
console.log(exportCmd);
var actionEvent = new AdfActionEvent(exportCmd);
console.log(actionEvent);
actionEvent.forceFullSubmit();
actionEvent.noResponseExpected();
actionEvent.queue(false);
setTimeout(function(){hidePopup();}, 1000);
}
function hidePopup() {
var popup = AdfPage.PAGE.findComponent("pt1:popupAceptarDescargarPlantilla::content");
popup.hide();
}
</af:resource>
You should have the following buttons:
<af:commandButton text="Aceptar" id="b17" visible="false" clientComponent="true" partialSubmit="true">
<af:fileDownloadActionListener contentType="excelHTML" filename="#{viewScope.mbGestionArchivos.nombre_archivo}" method="#{viewScope.mbGestionArchivos.generateExcelVacio}"/>
</af:commandButton>
<af:button text="Aceptar" id="botonPrueba" actionListener="#{viewScope.mbInformeDetalle.prepareForDownloadAction}" clientComponent="true" partialSubmit="true"></af:button>
This is the java method called by the button :
public void prepareForDownloadAction(ActionEvent act) {
FacesContext context = FacesContext.getCurrentInstance();
ExtendedRenderKitService erks =
Service.getService(context.getRenderKit(),
ExtendedRenderKitService.class);
erks.addScript(context, "customHandler();");
}
The hidden button is triggered using javascript a ADF methods, the magic happen in the setTimeout, When executing this function we avoid for a second to make submit but the request travels to the server, here we can observe how the file is started.
Ideally this.myPopUp.hide(); should close the popup but if it is not working for some reason, you can try closing the popup using javascript like:
public static void hidePopup(String popupId){
if (popupId != null)
{
ExtendedRenderKitService service =
Service.getRenderKitService(FacesContext.getCurrentInstance(),
ExtendedRenderKitService.class);
StringBuffer hidePopup = new StringBuffer();
hidePopup.append("var popupObj=AdfPage.PAGE.findComponent('" + popupId +
"'); popupObj.hide();");
service.addScript(FacesContext.getCurrentInstance(), hidePopup.toString());
}
}
You can get the popup clientId that you can pass into hidePopup using: this.myPopUp.getClientId(FacesContext.getCurrentInstance());
I am a learner.
I am trying to automate the logout functionality of Gmail using Selenium Webdriver but unable to do so ..
There are two Phases in logout, first click the Right Link at the top, if that box appears then click logout. iam unable to do so.
<span id="gbi4t" style="max-width: 76px; text-align: left;">Mahmood Ali</span>
<a id="gb_71" class="gbqfbb" href="?logout&hl=en&hlor" onclick="gbar.logger.il(9,{l:'o'})" role="button" target="_top">Sign out</a>
here is my xpath
//*[#id="gbi4t"] -> Clicking that top to get the logout pop up
//*[#id="gb_71"] -> To logout the gmail application
i have tried such as
driver.findElement(By.id("gbi4t")).click(); OR
driver.findElement(By.xpath("//*[#id='gbi4t']")).click();
driver.findElement(By.id("gb_71")).click(); OR
driver.findElement(By.xpath("//*[#id='gb_71']")).click();
Some ideas out there ?
Actually the <span> isn't recognized as an element.
You need to use the <a id="gbg4" ...> to click() on it, wait the pop up and click on the <a id="gb_71" class="gbqfbb" ...> to logout.
I let you code, since you need to pracctice :P
tell me what's up.
Suggestions :
What i can suggest to you is to use the cssSelector().
why ? Because it's faster than the xpath and when page like google or others use dynamic value used for id/name it's better to use the class attribute and cssSelector() is way better than others.
But sometimes you'll use xpath to find an element that has "cancel" as inner text (exemple : <a>cancel</a> )
cssSelector() reference
You can also try following:
driver.find_element(:id, "gbgs4dn").click
driver.find_element(:id, "gb_71").click
This worked for me.
This code certainly works for me:
// (after logging to google.com)
WebDriverWait wait = new WebDriverWait(driver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("gbi4t")));
//open overlay
driver.findElement(By.id("gbi4t")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("gb_71")));
//press logout
driver.findElement(By.id("gb_71")).click();
Heres a solved example ::
package testme;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class testexample {
public static WebDriver driver;
public static WebElement element;
public static void main(String args[]) throws InterruptedException {
//setting the chrome driver
System.setProperty("webdriver.chrome.driver", "C:/Users/workspace/Downloads/chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://www.gmail.com");
element =driver.findElement(By.linkText("Sign in"));
element.click();
Thread.sleep(1000);
element = driver.findElement(By.id("Email"));
element.sendKeys("yourusername#gmail.com");
element = driver.findElement(By.id("Passwd"));
element.sendKeys("yourpassword");
element.submit();
Thread.sleep(1000);
//click on the logout link step 1
element = driver.findElement(By.xpath("//*[#id='gb']/div[1]/div[1]/div/div[3]/div[1]/a"));
element.click();
// click on actual logout button step 2
element = driver.findElement(By.id("gb_71"));
element.click();
//closing the webdriver window after successful completion of the test
driver.close();
}
}
I am using Selenium webdriver. I can log in to the application, but while logging out it gets stuck, reason it cannot find logout link. I tried to find it byLink and byId. I have also tried using thread.sleep() but nothing seems to be working.
Logout link is present in all the pages.
HTML code:
<li>#{loginView.loggedInUser}>
<ul><li><h:link value="Administration" outcome="Administration.xhtml" /></li>
<li><h:commandLink value="Logout" actionListener="#{loginView.logout}">
<f:param id="userName" value="#{loginView.username}" />
</h:commandLink></li>
</ul></li>
SELENIUM code:
Thread.sleep(5000);
WebElement logOut = findElementByLinkText("Logout");
logOut.click();
assertEquals("Please sign in: ", findElementBySelector("h3.loginTitle.centerAlign").getText());
Use this code check how many links are present on page if it contains your logout link then you can click on it by using locator "linktext".
public void Link(){
driver.get(baseUrl);
HtmlTagFinder links = LinkFinder.links();
List<WebElement> allLinks = (List<WebElement>) links.findFrom(driver);
System.out.println(allLinks.size());
int i = 1;
for(WebElement link : allLinks){
System.out.println(i);
System.out.println(link.getText());
i++;
}
driver.close();
driver.quit();
}
driver.findElement(By.xpath("#value='Logout'")).click();