issue with sendKey inside if statement - java

I'm working on an auto login using Selenium. I'm able to open the browser and enter and submit the username just fine, but after entering the username, it will sometimes ask you to enter your secret question answer. for whatever reason, it just refuses to enter the secret question answer. oddly enough, it will also occasionally tell me it's unable to locate the element of the text box, but other times it will run and never give the error. Everything seems to work fine up until the if statement, and then it all falls apart.
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Example {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
String expectedURL = "https://mblogin.verizonwireless.com/amserver";
driver.get("https://sso.verizonenterprise.com/amserver/sso/login.go");
WebElement userId = driver.findElement(By.name("userId"));
userId.sendKeys("username");
userId.submit();
if(driver.getCurrentUrl().equals(expectedURL)){
WebElement answer = driver.findElement(By.name("answer"));
answer.sendKeys("test");
answer.submit();
}
}
}
The if statement itself should be fine, as I have been able to test it by outputting messages to the console, but it doesn't seem to want to fill in the text box and submit the answer.

I think you should try waiting for URL to change with a custom Expected Condition provided here.

Related

Picking element in iframe using Selenium Java / not able to accept GDPR consent window via automation

I am trying to accept the GDPR Consent window via Selenium (Java), which is placed in an iframe. I understood from the lecture and forums that I have to first switch to that frame (which I did) and then click on the button. However, nothing happens.
Can anyone please help?Thanks
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class GDPRiframe {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "/Users/DDD/WebDrivers/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://demo.guru99.com/test/");
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
WebElement frameelement = driver.findElement(By.xpath("//iframe[#id='gdpr-consent-notice']"));
driver.switchTo().frame(frameelement);
driver.findElement(By.xpath("//button[#id='save']")).click();
}
}
Verified the css of the object via console, if there is no issue with that - appears to be ok. Also, I tried to click on a link within the frame, also not working. Seems as if I was not switched to the frame.
Thanks

Selenium no such element exists

I am trying to perform a simple checkout flow on my staging website, but I cant seem to find the element. I tried to use selenium IDE which works but when it comes to coding in java I keep getting stuck on secure checkout
this is the element button I want to click
<a class="checkout-anchor click-button display-flex vertical-align-center justify-center" href="javascript:void(0);" onclick="onCheckout()" data-stepid="cartstep04">
<img src="https://release.squareoffnow.com/public/assets/images/checkout/svg/secure.svg" class="secure-pic ls-is-cached lazyloaded" alt="">Secure Checkout</a>
This is the code i have written so far
package googleTestCases;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class simpleCartFlow {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","/Users/manavmehta/Desktop/squareoffSeleniumProjects/chromedriver");
WebDriver driver=new ChromeDriver();
driver.get("http://release.squareoffnow.com/");
driver.manage().window().setSize(new Dimension(1440, 789));
driver.findElement(By.linkText("Products")).click();
driver.findElement(By.cssSelector(".store-buy-pro-button")).click();
driver.findElement(By.cssSelector(".pro-twinpack-button")).click();
driver.findElement(By.cssSelector(".whole-purchase-button")).click();
driver.findElement(By.cssSelector(".productAvailability > .click-button")).click();
driver.findElement(By.cssSelector(".giftpackSubmit")).click();
System.out.println("button not clicked");
driver.findElement(By.cssSelector(".checkout-anchor")).click();
System.out.println("button clicked");
driver.quit();
}
}
instead of using a CSS selector I also tried to use linkText but it still didn't work
I keep getting this error
I suspect your issue is due to not waiting long enough for the element to appear. I ran the following successfully using the exact same selectors you had (although with Python instead of Java):
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_base(self):
self.open("https://release.squareoffnow.com/")
self.click_link("Products")
self.click(".store-buy-pro-button")
self.click(".pro-twinpack-button")
self.click(".whole-purchase-button")
self.click(".productAvailability > .click-button")
self.click(".giftpackSubmit")
self.click(".checkout-anchor")
Full disclosure: This particular framework, SeleniumBase is one that I personally built, and it uses smart-waiting to make sure that elements have fully loaded before taking action. Java probably has something similar so that you can wait for the element to be clickable so that you don't have to sleep for an arbitrary amount of time between steps.

Ashot is not taking screenshot of correct element

I am trying to take screenshot of the table given in one webpage. and the same element xpath I am providing in the code however Ashot code is capturing screenshot of some other location.
I have also tried other code of taking screenshot,
Screenshot screenshot = new AShot().takeScreenshot(driver,driver.findElement(By.xpath(webElementXpath)));
but it was giving me error which I was able to fix by reading this link: https://github.com/pazone/ashot/issues/93 and then I used below code:
WebElement myWebElement = driver.findElement(By.xpath("//center/table/tbody/*"));
Screenshot fpScreenshot = new AShot()
.coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver,myWebElement);
ImageIO.write(fpScreenshot.getImage(),"PNG",new File("/Users/sanatkumar/eclipse-workspace/com.ScreenshotUtility/Screenshots/error.png"));
Please help as this code is giving me the screenshot of some random part of the webpage. I tried to capture other element as well but again I did not get the correct screenshot:
Please note my table is not fully visible on the webpage, manually I have to scroll down to view full table. do I need to write other code to get full screenshot of the table??
also my website is angular based which I am trying to automate using selenium java. the reason why I am doing this is because in protractor I dint find any API like Ashot. if anybody knows about it please let me know.
By adding a shootingStrategy I was able to capture just the form element with the attribute id = "post-form" at the bottom of this page.
From the documentation at https://github.com/pazone/ashot
Different WebDrivers take screenshots differently. Some WebDrivers
provide a screenshot of the entire page while others handle the
viewport only.
...
There are built-in strategies in ShootingStrategies for different use cases.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
import javax.imageio.ImageIO;
import java.io.File;
public class Main
{
public static void main(String args[]) throws Exception
{
System.setProperty("webdriver.gecko.driver", "./geckodriver");
System.setProperty("webdriver.firefox.bin", "/usr/bin/firefox");
WebDriver driver = new FirefoxDriver();
driver.get("https://stackoverflow.com/questions/54724963/ashot-is-not-taking-screenshot-of-correct-element");
Thread.sleep(2000);
WebElement webElement = driver.findElement(By.id("post-form"));
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver,webElement);
ImageIO.write(screenshot.getImage(),"PNG",new File("/home/dan/ElementScreenshot.png"));
Thread.sleep(2000);
driver.quit();
}
}
Outputs:
This functionaity is possible with Protractor also by requiring an NPM module like 'protractor-image-comparison'. If you wanted to capture the related posts on the sidebar for instance you could use the following code.
Note: I haven't tested this package out with large elements that extend past the range of the browser viewport so can't say how they will work on those.
Spec File
describe('simple test', () => {
it('will save image', async () => {
await browser.get("https://stackoverflow.com/questions/54724963/ashot-is-not-taking-screenshot-of-correct-element");
await browser.driver.sleep(10 * 1000);
let related_questions_sidebar = element(by.className('module sidebar-related'));
await browser.executeScript('arguments[0].scrollIntoView();', related_questions_sidebar);
await browser.driver.sleep(3 * 1000);
// saveElement
await browser.protractorImageComparison.saveElement(related_questions_sidebar, 'sidebar-image');
});
});
Conf.js- in your OnPrepare
onPrepare: async () => {
// await jasmine.getEnv().addReporter(new dbReporter());
const protractorImageComparison = require('protractor-image-comparison');
browser.protractorImageComparison = new protractorImageComparison(
{
baselineFolder: './screen-compare/baselines/',
screenshotPath: './screen-compare/screenshots/'
}
);
);
Image Saved

Unable to click on Facebook "setting" link through selenium webdriver with java

My Java
package com.palash.healthcare;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class Login {
#Test
#Parameters({"URL","USERNAME","PASSWORD"})
public static void logindata(String url,String Username,String Password)
{
WebDriver driver = new FirefoxDriver();
driver.get(url);
driver.manage().window().maximize();
driver.findElement(By.id("email")).sendKeys(Username);
driver.findElement(By.id("pass")).sendKeys(Password);
driver.findElement(By.id("u_0_v")).click();
driver.findElement(By.id("userNavigationLabel")).click();
//driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
//driver.findElement(By.xpath("//span[#class='_54nh'][text()='Settings']")).click();
List<WebElement> All_List = driver.findElements(By.xpath("//ul[#class='_54nf']"));
for(WebElement li:All_List)
{
System.out.println(li.getText());
if(li.getText().equalsIgnoreCase("Settings"));
li.click();
}
}
}
I am writing the facebook Setting link script in selenium webdriver with java but I am unable to click on the Setting link also i have tried the above code.Can Anybody Help? and for the html about the script you can see the facebook Setting link right above the "logout" button.
Not too sure what's going on with that list. I don't think you'll need that but correct me if I'm wrong.
The web app I do work for is really wonky and sometimes you have to do some weird stuff. Try something like:
Actions actions = new Actions(driver);
WebElement settings = driver.findElement(By.xpath("//span[#class='_54nh'][text()='Settings']"));
actions.moveToElement(settings).build().perform();
settings.click();
This kinda breaks the .click() down into smaller steps.
Took me a long while to get .click() commands down. They behave differently on different web applications.
Let me know if that works.
Have you considered just navigating to the settings page after you log in? It's https://www.facebook.com/settings.
driver.findElement(By.id("userNavigationLabel")).click();
Thread.sleep(3000);
driver.findElement(By.xpath("//span[#class='_54nh'][text()='Settings']")).click();
Got the Answer Just Need to reconstruct the Xpath.

Java Performing Actions on a Website

Yesterday I posted this Retrieving Data in Java . I'm curious it is possible to make a java program run while a web browser is open and then have it do stuff on a website. If I have facebook open on a browser, could it type the current time in the status box and then click post? Or let's say I make the program able to take input from the user (perhaps using scanner?) and then based on the input, it could load google, type it into the search bar and then click search.
You can do this by using Selenium:
Selenium automates browsers. That's it. What you do with that power is
entirely up to you. Primarily it is for automating web applications
for testing purposes, but is certainly not limited to just that.
Boring web-based administration tasks can (and should!) also be
automated as well.
This is example from documentation page which searches for the term “Cheese” on Google:
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Selenium2Example {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});
// Should see: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
//Close the browser
driver.quit();
}
}

Categories

Resources