Selenium+Java - Unable to find WebElements in page - java

I'm doing some automation bits for work and right now I'm trying to automate a purchase through our storefront that should go to the paypal sandbox and complete the purchase. Everything looks good and I know the general flow works but I'm having trouble finding the webElements when I get to the first PayPal page.
The PayPal side of the flow consists of 2 pages. One to input the login information and another one to confirm the purchase. The second page works perfectly but the first one always gives me "Unable to find element" when I tell it to look for the email/password field and the login button. If make the driver print out the current URL for debugging purposes it correctly prints the payPal URL so it is looking at the right site. I also tried putting a 30 seconds delay to make sure it wasn't a timing issue and I get the same problem.
Here's the class file in question:
public class PayPalLoginPage extends AbstractPaymentPage {
//AbstractPaymentPage extends from AbrstractPageObject
private WebElement email; //Element ID is email
private WebElement password; //Element ID is password
#FindBy(id = "btnLogin")
private WebElement loginButton;
public PayPalLoginPage(WebDriver driver) {
super(driver);
PageFactory.initElements(driver, this);
}
public PayPalPurchaseConfirmationPage login (PayPalInfo payPalInfo) {
email.sendKeys(payPalInfo.getEmail());
password.sendKeys(payPalInfo.getPassword());
loginButton.click();
this.waitForPayPalLoadingCurtainToDisappear();
return new PayPalPurchaseConfirmationPage(this.getDriver());
}
The way I'm calling this class is like this:
case PAYPAL_PURCHASE:
setDriver(new PayPalLoginPage(getDriver()).login(getPaymentMethod()).confirmPayPalPurchase());
break;
So, the flow works perfectly up until it gets to the first payPal page and it just stops saying it can't find any of those 3 elements. If I set it to just wait there and manually fill up the information then it picks right up on the next page and works from them on (finding all the elements on the 2nd payPal page and acting on them).
I get the same behavior if I put the findElement.By line inside the login method and also the same result regardless of whether I'm trying to find them using id, name, xpath or css.
Any idea on what I could be missing?.

You are just defining the email and followings as WebElement but not assigning them to any webelement. See the following:
private WebElement email = driver.findElement(By.id("email_text_box_id"));
private WebElement password = driver.findElement(By.id("password_text_box_id"));
private WebElement loginbutton = driver.findElement(By.id("login_button_id"));
if you want PageObject to assign WebElements then you need to call the initElement inside of a case:
public class PayPalLoginPage extends AbstractPaymentPage {
//AbstractPaymentPage extends from AbrstractPageObject
private WebElement email; //Element ID is email
private WebElement password; //Element ID is password
#FindBy(id = "btnLogin")
private WebElement loginButton;
public PayPalPurchaseConfirmationPage login (PayPalInfo payPalInfo) {
email.sendKeys(payPalInfo.getEmail());
password.sendKeys(payPalInfo.getPassword());
loginButton.click();
this.waitForPayPalLoadingCurtainToDisappear();
return new PayPalPurchaseConfirmationPage(this.getDriver());
}
}
Call the PayPal login function:
public class UsingPayPalLoginPage {
public static void main(String[] args) {
// Create a new instance of a driver
WebDriver driver = new HtmlUnitDriver();
// Create a new instance of the PayPall page
// and initialise any WebElement fields in it.
PayPalLoginPage page = PageFactory.initElements(driver, PayPalLoginPage.class);
// call login of paypal.
page.login(payPalInfo);
}
}

Related

Not able to locate an element within the IFrame (Selenium)

So i have create successful test of adding a card to my profile and now i would like ot verify if card was added so i would like to check if "Your card was successfully added" text appeared, however for some kind of a reason the className not located.
This is an iframe however i do enter it to add the card details and submit them, so trying to understand why it cant locate the follow:
Adding card
public void addCard(Card card) {
switchToCardIframe()
.fillInCardNumber(card.getCardNumber())
.fillInCardHolder(card.getCardHolderName())
.fillInExpiryDate(card.getExpiryDate())
.fillInCvv(card.getCvv())
.clickOnToggle()
.clickOnAddButton();
}
This is how i locate the text
#FindBy(css = "payment-state-message")
private WebElement cardAddedIndicator;
Test
#Test
public void shouldSuccessfullyAddCard() {
myCards.addCard(cardData());
assertTrue(myCards.getCardAddedIndicator().isDisplayed());
}
I have also tried to check if another element displayed by escaping the iframe but no luck so any help appreciated
driver.switchTo().defaultContent()
I have also attempted Thread.sleep() for 10 seconds before taking getting the text from the css locater but not luck
Here is the base page where wait initialized
public class BasePage {
public WebDriver driver;
protected Wait wait;
public BasePage(WebDriver driver) {
initializePage(driver);
this.wait = new Wait(driver);
}
final protected void initializePage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(new AjaxElementLocatorFactory(driver, 20), this);
}
}
Your css is wrong, so instead of
#FindBy(css = "payment-state-message")
private WebElement cardAddedIndicator;
try this
#FindBy(css = ".payment-state-message")
private WebElement cardAddedIndicator;
also do not check for visibility by .isDisplay
rather have a text method called on it. Put some delay/wait as well.
String actualMessage = myCards.getCardAddedIndicator().getText();
String expectedMessage = "Your card was successfully added"
then assert these two based on their actual and expected behavior .
Conclusion :
When there is an iframe form and you submit it, it does not mean that its still the same iframe. In my case when I submitted the form then iframe disappeared however in order for for the element to be located I had to perform driver().switch().parentFrame()
FYI: First always check your locators and make sure they are right.

Not able to call the webelement method in order to pass the parameter of login detail. Working with PageObject

This is my HomePage of Page Object where I created WebElement of UserName method and now want to call it in test case case but it not working.
Showing me the error on element line.
public class HomePage {
WebDriver driver;
By username = By.xpath("/html[1]/body[1]/form[1]/table[1]/tbody[1]/tr[1]/td[2]/input[1]");
By password = By.xpath("/html[1]/body[1]/form[1]/table[1]/tbody[1]/tr[2]/td[2]/input[1]");
By login = By.xpath("/html[1]/body[1]/form[1]/table[1]/tbody[1]/tr[3]/td[2]/input[1]");
static WebElement element = null;
//Experiment with webelement
public static WebElement UserName(WebDriver driver) {
element.findElement(By.xpath("/html[1]/body[1]/form[1]/table[1]/tbody[1]/tr[1]/td[2]/input[1]"));
return element;
}
public static WebElement Password(WebDriver driver) {
element.findElement(By.xpath("/html[1]/body[1]/form[1]/table[1]/tbody[1]/tr[2]/td[2]/input[1]"));
return element;
}
public static WebElement ClickLogin(WebDriver driver) {
element.findElement(By.xpath("/html[1]/body[1]/form[1]/table[1]/tbody[1]/tr[3]/td[2]/input[1]"));
return element;
}
}
These are the code of test class
//objLogin = new HomePage();
HomePage objLogin = new HomePage();
//input the username, password and click login.
objLogin.UserName(driver).sendKeys("mngr279645");
objLogin.Password(driver).sendKeys("YzarAzy");
objLogin.ClickLogin(driver).click();
Any help will be appreciated.....
First of all I don't understand why would you need WebDriver driver as you parameter in every selector when you are no using it and it shouldn't be there.
And second I suggest you study more of a PageObject architecture and using Xpath in general. In your comment above I still cannot see error message being shown.
By changing the scope in pom.xml from test to compile . It's Worked for me

JAVA - Selenium WebDriver - Assertions and Waits

I am having a problem with my Assertion, or rather with the "time" the assertion is being executed. So, the assertion is working as it should, however, it is going too fast, as it is executing without waiting for the page it should be targeting to load. Which means that the assertion is failing the test.
Having this in mind, I tried searching around how to add a "wait" to the assert to make it wait for the page to load before running, but with no success.
So, would anyone, please be able to help with this, as in how would I code so, that the assert "waits" for the page to load and then executes?
I've tried adding the wait to the header method, i tried adding the wait to the test script, but no success.
public class test1 extends DriverSetup{
//Here we are setting the method to use the homePage
private HomePage homePage = new HomePage(getDriver());
//Here we are setting the method logInPage
private AuthenticationPage authenticationPage = new AuthenticationPage(getDriver());
//Here are setting the method CreateAccountPage
private CreateAccountPage createAccountPage = new CreateAccountPage(getDriver());
//Here we are setting the method to access the Website HomePage with the driver
private void accessWebsiteHomePage (){
getDriver().get("http://automationpractice.com/index.php");
}
#Test
public void CreateAccount() {
accessWebsiteHomePage();
//Log in
homePage.logInBut();
//Authentication page "Create a new account" box
authenticationPage.setCreateAccountEmailAddress(emailGenerator.Email());
authenticationPage.CreateAccountButtonClick();
Assert.assertEquals("CREATE AN ACCOUNT", createAccountPage.HeaderCheckRightPage());
The assert should be targeting the "CREATE AN ACCOUNT" page, but it is targeting the "AUTHENTICATION" page, which comes before it, hence the test fails as the "actual" value being printed is the "AUTHENTICATION" page, not the "CREATE AN ACCOUNT" page.
You need to use an explicit wait. Here is one that will wait for the title to be equal to something:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return driver -> driver.getTitle().equals(searchString);
}
You can make it more reliable by forcing the case of what you want to match like this:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return driver -> driver.getTitle().toLowerCase().equals(searchString.toLowerCase());
}
You would then need to put the following in before your assertion:
WebDriverWait wait = new WebDriverWait(driver, 10, 100);
wait.until(titleIsEqualTo("CREATE AN ACCOUNT"));
I'm making the assumption that by header you mean the page title since you haven't shown the code that collects the header.
*Edit*
A non-lambda version of the above ExpectedCondition is:
private ExpectedCondition<Boolean> titleIsEqualTo(final String searchString) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
return driver.getTitle().toLowerCase().equals(searchString.toLowerCase());
}
};
}

Generating Java cssSelector to click span element in Selenium

I'm calling IE driver to launch this webpage (Business Objects). I'm able to login with the credentials. I need to click on a element on the next page. Need help writing the java to read this element and click.
<span style="white-space:nowrap;" class="iconText" id="IconImg_Txt_btnListing">Document List</span>
This is what I got so far using firebug-firepath.
driver.switchTo().defaultContent();
pickObj = driver.findElement(By.cssSelector("#IconImg_Txt_btnListing"));
pickObj.click();
Update: Another attempt-
public class InitComp {
//private WebDriver driver;
#FindBy(how = How.CSS, using = "#IconImg_Txt_btnListing") private WebElement DocListBtn;
public void clickDocList() {
DocListBtn.click();
}
}
This class is called as-
InitComp init = new InitComp();
PageFactory.initElements(driver, init);
init.clickDocList();
This does not help either though. Throws me an exception - "ElementNotFound". This page happens to be the first page after login. Where am I going wrong?
Thanks.
Arya

How to verify a page title using WebDriver and page object?

I am trying to write a method to verify page title using page objects but I am unable to do it. Could you please help me out how to write a method to verify page title after searching something in the google page.
Here is my 2 classes.
Class 1
public class GoogleSearchPage {
protected WebDriver driver;
#FindBy(name="q")
private WebElement SearchBox;
#FindBy(name="btnG")
private WebElement SearchButton;
public void SearchFor(String SearchTerm)
{
SearchBox.sendKeys(SearchTerm);
SearchButton.click();
}
}
Class2
public class TestSearchResults {
WebDriver driver;
GoogleSearchPage page;
#BeforeClass
public void Launch() throws Exception
{
driver = new FirefoxDriver();
driver.get("http://google.com");
}
#AfterClass
public void Close()
{
driver.quit();
}
#Test
public void ResultPage() {
System.out.println(page);
page=PageFactory.initElements(driver, GoogleSearchPage.class);
page.SearchFor("selenium");
}
}
Could you please help how to verify the title after displaying the Search results
Note: I am using TestNG.
Thanks in Advance,
Shiva Oleti.
Try this:
assertEquals("Your Page Title" , driver.getTitle());
driver.getTitle() - Returns Title of your current page.
You can get & verify title of page using python webdriver. See below codes
driver.title('title name')
assert 'title name' in driver.title('title name')
It will verify the title name. if it is there title name test case pass else through assert error.
Create a constructor in each page object. The constructor:
sets the instance driver value
waits for page load to complete (e.g. loading spinner not visible, jQuery.active == 0, document.readyState == 'complete')
verifies the page title (see other answers)
Issue PageFactory.initElement(driver, this);
Therefore you don't need a separate method to verify title. In each step you will have a new YourPageObjectPage() which checks the title automatically. Think DRY.

Categories

Resources