I have a tricky situation:
I am handling two popups after entering login info, but on the second pop-up I am not able to consistently hit the OK button every time
I have tried Waits, Storing Element in List and Switch cases
public class loginUser {
public static WebDriver driver = new InternetExplorerDriver();
public static void winHandles()
{
String newHandle = null;
Set<String> newHandles = driver.getWindowHandles();
Iterator<String> itr = newHandles.iterator();
while(itr.hasNext()){
newHandle = itr.next();
driver.switchTo().window(newHandle);
System.out.println(driver.getCurrentUrl());
}
}
public static void main(String args[]) throws InterruptedException
{
System.setProperty("","");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("");
driver.findElement(By.name("")).sendKeys("");
driver.findElement(By.name("")).sendKeys("");
driver.findElement(By.name("")).sendKeys("");
driver.findElement(By.id("")).click();
String parentWindowHandler = driver.getWindowHandle();
winHandles();
List<WebElement> yesbutton = driver.findElements(By.id("btnYes"));
for (int i = 0; i < 4; i++) {
if(yesbutton.get(0).isDisplayed())
{
yesbutton.get(0).click();
}
else {
System.out.println("button is creating problems");
}
}
driver.switchTo().window(parentWindowHandler);
System.out.println(driver.getCurrentUrl());
winHandles();
Thread.sleep(3000);
List<WebElement> okbutton = driver.findElements(By.id("btnOK"));
for (int i = 0; i < 4; i++) {
if(okbutton.get(0).isDisplayed())
{
okbutton.get(0).click();
}
else {
System.out.println("button is creating problems");
}
}
Thread.sleep(7000);
winHandles();
driver.findElement(By.name("")).click();
driver.findElement(By.id("")).click();
driver.findElement(By.name("")).click();
driver.findElement(By.id("")).click();
driver.findElement(By.name("")).click();
driver.close();
}}
So, this is the hard coded version
The locator with id btnOK is causing problems mostly.
Like 4 out of 5 times
I also have the same kind of issue while running test in firefox but in chrome, test runs successfully. You can use try catch :
try
{
okbutton.get(0).click();
}
catch(Exception e)
{
}
This is not advisable but due to browser compatibility, i had to use this as a temporary solution.If anyone has real solution kindly update me too...
Related
I have a page with JavaScript code that polls an API every second and replaces and element in the HTML page with the response. I would like to test this page using Selenium WebDriver. I have WebDriver setup in my Junit Test but I don't know how to deal with the polling Java Script.
RemoteWebDriver driver = chrome.getWebDriver();
driver.get("http://localhost:8080");
The JavaScript code configures a timer to call the getMessage() is setup like so.
<body>
<h1 id="message"> Loading ... </h1>
</body>
<script>
function getMessage()
{
$.ajax({
url : '/message',
type: 'GET',
success: function(data){
$('#message').text(data.message);
},
error: function (data) {
$('#message').text("Error Response");
}
});
}
$(document).ready(function() {
window.setInterval(getMessage, 1000);
});
</script>
I want to test the H1 message value changed to something every second or so for 30 seconds, so I am expecting to see 25 changes in 30 second run of the test. How can I do this with Selenium WebDriver?
Below is one of the hacky way of printing the message every two seconds
We can write our own function and pass that function to Until method of FluentWait. It will call this method every 2 second & Timeout is set to 30 seconds. We are using counter Once count > 10 . It should come out of until . May need some refactoring as per your needs.
Function<WebDriver, Boolean> function = new Function<WebDriver, Boolean>()
{
int count = 1;
public Boolean apply(WebDriver arg0) {
count++;
WebElement element = arg0.findElement(By.id("message"));
String text= element.getText();
System.out.println("Message " + text); // your logic
if(count > 10))
{
return true;
}
return false;
}
}
Example use . Assuming driver paths etc. are set properly
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://localhost:8080");
FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
wait.pollingEvery(Duration.ofSeconds(2));
wait.withTimeout(Duration.ofSeconds(30));
wait.ignoring(NoSuchElementException.class);
Function<WebDriver, Boolean> function = new Function<WebDriver, Boolean>()
{
int count = 1;
public Boolean apply(WebDriver arg0) {
count++;
WebElement element = arg0.findElement(By.id("message"));
String text= element.getText();
System.out.println("Message " + text); // your logic
if(count > 10))
{
System.out.println(count + "++++++++++++++++++");
return true;
}
return false;
}
};
wait.until(function);// You can handle timeout exception using try-catch as per your
//use case
}
Here is another approach:
private boolean testElementFor1SecChange(SearchContext searchContext, By locator, Duration testDuration){
String baseElementText = searchContext.findElement(locator).getText();
for(int i = 0; i < testDuration.get(ChronoUnit.SECONDS); i++){
try {
Thread.sleep(1000);
String nextElementText = searchContext.findElement(locator).getText();
if(baseElementText == null || baseElementText.equals(nextElementText)){
return false;
}
} catch (InterruptedException e) {
e.printStackTrace();
return false;
}
}
return true;
}
So the test would look like:
#Test
public void testChanges(){
driver.get("http://localhost:8080");
Assert.assertTrue(
testElementFor1SecChange(driver, By.id("message"), Duration.ofSeconds(30))
);
}
I'm trying to type selenium in google and get all the title text of result in a notepad file. i want to get all available links on all the pages, till last page of search. but only 1st page's link i am getting. when i debug and run, it is working for some 10 pages.help me in this.
JAVA code:
public class weblink
{
public static void main(String[] args) throws IOException, InterruptedException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "E:\\disha.shah/myWork/eclipse/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("_fZl")).click();
PrintStream ps = new PrintStream(new File(("E:\\disha1.txt")));
do
{
List<WebElement> findElements = driver.findElements(By.xpath("//*[#id='rso']//h3/a"));
for (WebElement webElement : findElements)
{
System.out.println("-" + webElement.getText()); // for title
//System.out.println(webElement.getAttribute("href")); // for links
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
System.setOut(ps);
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
Thread.sleep(1000);
if(driver.findElement(By.linkText("Next")).isDisplayed()== true)
{
driver.findElement(By.linkText("Next")).click();
}
else
{
System.out.println("All Link is Covered");
}
}
while(driver.findElement(By.linkText("Next")).isDisplayed() );
{
//Thread.sleep(2000);
}
}
}
I've done some correction. the updated code is below.-
public static void main(String[] args) throws IOException, InterruptedException
{
WebDriver driver;
System.setProperty("webdriver.chrome.driver", "D:/Application/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("http://www.google.co.in/");
driver.findElement(By.id("lst-ib")).sendKeys("Selenium");
driver.findElement(By.id("_fZl")).click();
Boolean nextButtonFlag = true;
// Create two separate file storing the result
PrintStream searchTitle = new PrintStream(new File(("D:\\Titles.txt")));
PrintStream searchLink = new PrintStream(new File(("D:\\Links.txt")));
do
{
List<WebElement> findElements = driver.findElements(By.xpath("//h3[#class='r']/a"));
for (WebElement element : findElements)
{
// Write all received links and title inn txt file
searchTitle.append(element.getText()+"\n");
searchLink.append(element.getAttribute("href")+"\n");
}
Thread.sleep(2000);
try
{
driver.findElement(By.linkText("Next")).click();
}
catch(Exception e)
{
// no more next button to navigate further link
nextButtonFlag=false;
}
Thread.sleep(2500);
}
while(nextButtonFlag);
System.out.println("Execution done");
searchTitle.close();
searchLink.close();
}
}
I want to open the mail by clicking on it, after receiving the activation mail.
For that I am using keyword driven framework.
So can anyone please let me know that how can we click on element without using List<>.
Because in my coding structure I am returning the object of Webelement instead of List<> object.
Note: Please suggest the solution without using JavaMail Api or if suggest please let me know according to the keyword driven framework.
Way of code structure where I find the elements in one method and in another method after getting an element perform the operations:
private boolean operateWebDriver(String operation, String Locator,
String value, String objectName) throws Exception {
boolean testCaseStep = false;
try {
System.out.println("Operation execution in progress");
WebElement temp = getElement(Locator, objectName);
System.out.println("Get Element ::"+temp);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//For performing click event on any of the button, radio button, drop-down etc.
if (operation.equalsIgnoreCase("Click")) {
temp.click();
}
/*Trying to click on subject line of "Email"*/
if (operation.equalsIgnoreCase("Click_anElement")) {
Thread.sleep(6000L);
Select select = new Select(temp);
List<WebElement> options= select.getOptions();
for(WebElement option:options){
System.out.println(option.getText());
}
/*try
{
if(temp.getText().equals(value)){
temp.click();
}
}
catch(Exception e){
System.out.println(e.getCause());
}*/
/*if (value != null) {
temp.click();
}*/
}
}
testCaseStep = true;
} catch (Exception e) {
System.out.println("Exception occurred operateWebDriver"
+ e.getMessage());
System.out.println("Taking Screen Shot");
TakesScreenshot ts=(TakesScreenshot)driver;
File source=ts.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(source, new File("./Screenshots/"+screenshotName+".png"));
System.out.println("Screenshot taken");
}
return testCaseStep;
}
public WebElement getElement(String locator, String objectName) throws Exception {
WebElement temp = null;
System.out.println("Locator-->" + locator);
if (locator.equalsIgnoreCase("id")) {
temp = driver.findElement(By.id(objectName));
} else if (locator.equalsIgnoreCase("xpath")) {
temp = driver.findElement(By.xpath(objectName));
System.out.println("xpath temp ----->" + temp);
} else if (locator.equalsIgnoreCase("name")) {
temp = driver.findElement(By.name(objectName));
}else if (locator.equalsIgnoreCase("cssSelector")) {
temp = driver.findElement(By.cssSelector(objectName));
}
return temp;
}
I came across many solutions for switching between windows, one of them is:
Set<String> allWindows = driver.getWindowHandles();
for(String currentWindow : allWindows){
driver.switchTo().window(currentWindow);
}
But, I am unable to go to a particular window. Can someone tell me how to switch to 3rd window from parent window (using java client library)?
You are almost there. If you want to switch to a window first store the window id's in an array and switch to some specific window. Some thing like below. Let me know if you want more help. Happy coding.
Set handles = driver.getWindowHandles();
String[] individualHandle = new String[handles.size()];
Iterator it = handles.iterator();
int i =0;
while(it.hasNext())
{
individualHandle[i] = (String) it.next();
i++;
}
driver.switchTo().window(individualHandle[1]);
public static void switchWindow(String text) {
WebDriver popup = null;
Iterator<String> windowIterator = driver.getWindowHandles()
.iterator();
while (windowIterator.hasNext()) {
String windowHandle = windowIterator.next();
popup = driver.switchTo().window(windowHandle);
String title = popup.getTitle();
if (title.contains(text)) {
break;
}
}
}
This will get you any window that contains certain text, you don't have to be specific.
The below method will navigate to a particular window
public static void switchToParticularWindow(WebDriver driver, int index) throws InterruptedException {
ArrayList<String> tabs = new ArrayList(driver.getWindowHandles());
driver.switchTo().window(tabs.get(index));
Thread.sleep(2000);
logger.info("Switched to new tab");
}
public class WindowHandles {
public static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.get("https://www.way2automation.com/lifetime-membership-club/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.findElement(By.xpath("//*[#id=\"menu-item-25089\"]/a/span[2]")).click();
driver.findElement(By.xpath("//*[#id=\"ast-desktop-header\"]/div[1]/div/div/div/div[2]/div/div/div/a[1]")).click();
Set<String> window = driver.getWindowHandles();
Iterator<String> it =window.iterator();
while(it.hasNext())
{
String childWindow = it.next();
String windowTitle = driver.switchTo().window(childWindow).getTitle();
if(windowTitle.contains("Way2Automation"))
{
break;
}
}
System.out.println(driver.getTitle());
driver.findElement(By.xpath("//*[#id=\"blueBarDOMInspector\"]/div/div/div/div[1]/a")).click();
System.out.println(driver.getTitle());
}
}
I am trying to use Selenium with JUnit and I am having trouble completing my tests because it seems like my button execution is only occurring once. here's some of the code:
JQueryUITab navTab = new JQueryUITab(driver.findElement(By.cssSelector("nav ul.tabs")));
try {
navTab.selectTab("Tab1");
} catch (Exception e) {
e.printStackTrace();
}
try {
navTab.selectTab("Tab2");
} catch (Exception e) {
e.printStackTrace();
}
System.out.print(navTab.getSelectedTab());
the console print out will read "Tab1". this JQueryUITab object is a custom object. here are the inner workings:
public String getSelectedTab() {
List<WebElement> tabs = jQueryUITab.findElements(By.cssSelector("li.tab"));
for (WebElement tab : tabs) {
if (tab.getAttribute("class").equals("tab selected")) {
return tab.getText();
}
}
return null;
}
public void selectTab(String tabName) throws Exception {
boolean found = false;
List<WebElement> tabs = jQueryUITab.findElements(By.cssSelector("li.tab"));
for (WebElement tab : tabs) {
if(tabName.equals(tab.getText().toString())) {
tab.click();
found = true;
break;
}
}
if (!found) {
throw new Exception("Could not find tab '" + tabName + "'");
}
}
There are no exceptions thrown. At least pertaining before or at this part of the code.
There were a couple problems wrong with my implementation. Firstly, it could have been improved by selecting not the li.tab object, but the a class inside of it. From there, there were 2 solutions that worked for me. First was using
webElement.sendKeys(Keys.ENTER);
and the second (imho more elegant solution) was to get the instance of the selenium driver object controlling the object and then get it to execute the command to click the tab. Here's the full corrected method.
public void selectTab(String tabName) throws Exception {
boolean found = false;
List<WebElement> tabs = jQueryUITab.findElements(By.cssSelector("li.tab a"));
for (WebElement tab : tabs) {
if(tabName.equals(tab.getText().toString())) {
// tab.sendKeys(Keys.ENTER);
WrapsDriver wrappedElement = (WrapsDriver) jQueryUITab;
JavascriptExecutor driver = (JavascriptExecutor) wrappedElement.getWrappedDriver();
driver.executeScript("$(arguments[0]).click();", tab);
found = true;
break;
}
}
if (!found) {
throw new Exception("Could not find tab '" + tabName + "'");
}
}