How to get an autocomplete to work with java webdriver? - java

I have the following selenium automation code that used to work for an autocomplete dropdown:
#FindBy(xpath = "//*[#id='s2id_customer-name-search']/a")
private static WebElement customerDrop;
#FindBy(id = "s2id_autogen5_search")
private static WebElement searchField;
public static void searchByCustomer(String customer) {
customerDrop.click();
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOf(searchField()));
searchField.sendKeys(customer);
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOf(searchResult()));
searchResult.click();
}
A change was made to the page in order to resolve an issue with clearing the field, and now the automation no longer autocompletes. Manual entry still triggers the autocomplete, but not with my automation code.
Is there another way to do this that will also trigger the autocomplete?

Related

Xpath does not capture the element even with the WebDriverWait

I am new to Selenium Testing and trying to locate the below input element using Xpath:
This is the username input element of the https://opensource-demo.orangehrmlive.com/web/index.php/auth/login website.
My code is:
private static final By USER_NAME_TEXT_BOX = By.xpath("//input[#placeholder='auth.username']");
private static final By PASSWORD_TEXT_BOX = By.xpath("//input[#placeholder='auth.password']");
private static final By LOGIN_BUTTON = By.xpath("//button[starts-with(#button, 'orangehrm-login-button')]");
private LoginPage setUserNameTextBox(String userName) {
PageActionsHelper.waitAndSendKeys(USER_NAME_TEXT_BOX,userName);
return this;
}
and the PageActionsHelper.waitAndSendKeys() is as follows:
public static void waitAndSendKeys(By by, String value) {
WebDriverWait wait = new WebDriverWait(getDriver(), 60);
WebElement element = wait.until(ExpectedConditions.presenceOfElementLocated(by));
//trigger the reaload of the page
getDriver().findElement(by).sendKeys(value);
// wait the element "Add Item" to become stale
wait.until(ExpectedConditions.stalenessOf(element));
// click on "Add Item" once the page is reloaded
wait.until(ExpectedConditions.presenceOfElementLocated(by)).sendKeys(value);
//getDriver().findElement(by).sendKeys(value);
}
I also checked below:
Cannot find any iframe wrapped this element.
When I execute
$x("//input[#name='username']") or
$x("//input[#placeholder='auth.username']") in the web console, it
locates correctly!
WebDriverWait does the waiting but empty
browser is loaded and just timeout with the below exception:
I was using Safari browser and the screenshot was taken from it.
When I use Chrome developer option, labels are totally different. (Bit strange)
When I open the link you shared I see somewhat different UI, the placeholder is different there, however I think the following locators should work for both cases:
private static final By USER_NAME_TEXT_BOX = By.xpath("//input[#name='username']");
private static final By PASSWORD_TEXT_BOX = By.xpath("//input[#name='password']");
private static final By LOGIN_BUTTON = By.xpath("//button");

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.

Selenium+Java - Unable to find WebElements in page

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);
}
}

Selenium Webdriver, Javascript link, Unable to locale Element

Hi I am facing this issue, Below is a code which i had generated using Selenium IDE, Basically i am trying to access a career portal of the particular website below and for the Jobposting QA specialist, I was experimenting to auto complete the application using Selenium.
1) I am not able to replicate the code working in webdriver despite adding the code under proper class and importing all the necessary packages.
2) On running it as a TestNG test, i have a failure showing Unable to find Element.
3) The link to the QA specialist is not being detected by the driver either if i give it as identify By.link text or By.xpath.
4) please guide me where i am making mistake.
5) I am a beginer to Selenium
public class Application {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.saymedia.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testApplication() throws Exception {
driver.get(baseUrl + "/jobs");
driver.findElement(By.linkText("QA Specialist")).click();
driver.findElement(By.linkText("Apply Now")).click();
driver.findElement(By.linkText("Send Application")).click();
}
Your elements are inside of an iframe. Selenium only interacts with elements in the current frame. Any element within a child frame cannot be interacted with until you switch into that frame. You can switch by using switchTo().frame():
driver.get(baseUrl + "/jobs");
driver.switchTo().frame("jobviteframe");
driver.findElement(By.linkText("QA Specialist")).click();
driver.findElement(By.linkText("Apply Now")).click();
driver.findElement(By.linkText("Send Application")).click();
The arguments for frame() are
number from 0
id of the frame
the webelement rerference of the frame
When done in the iframe, use the following to exit back to the top of the document:
driver.switchTo().defaultContent();

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

Categories

Resources