PhantomJS submit button not clicked - works in Selenium - phantomjs

I am having difficult with the submit button, it is not clicked in phantomJS the same code when run in Selenium works.
Does anybody have any suggestions (in Java) ?
public class BookFlight
{
WebDriver driver;
File file = new File("C:/Program Files/phantomjs-2.1.1-windows/bin/phantomjs.exe");
#Test
public void homePageFlightDetails() throws Exception
{
//Setup GhostDriver
System.setProperty("phantomjs.binary.path", file.getAbsolutePath());
//***************************************************
// FIREFOX UI DEBUG - Set debug to True for UI debug
boolean debug=false;
if (debug)
{
driver= new FirefoxDriver();
driver.manage().window().maximize();
}
else
{
driver=new PhantomJSDriver();
//Set logging to Severe Logger.getLogger(PhantomJSDriverService.class.getName()).setLevel(Level.SEVERE);
}
//***************************************************
//Submit Home page and get the title
driver.get("http://www.aa.com");
String pageTitle = driver.getTitle();
System.out.println("The Current page title is "+pageTitle);
//Find the origin airport field
WebElement originAirport=driver.findElement(By.id("reservationFlightSearchForm.originAirport" ));
//Clear any existing text and enter the origin airport
originAirport.clear();
originAirport.sendKeys("PHX");
//Find the destination airport field
WebElement destAirport=driver.findElement(By.id("reservationFlightSearchForm.destinationAirport" ));
destAirport.clear();
destAirport.sendKeys("LAS");
//Find the depart date field
WebElement depDate = driver.findElement(By.id("aa-leavingOn"));
depDate.clear();
depDate.sendKeys("08/20/2016");
//Find the return date field
WebElement retDate = driver.findElement(By.id("aa-returningFrom"));
retDate.clear();
retDate.sendKeys("08/24/2016");
//Find the Search up button
// WebElement searchButton = driver.findElement(By.id("flightSearchForm.button.reSubmit"));
// driver.findElement(By.id("flightSearchForm.button.reSubmit")).click();
// WebElement searchButton = driver.findElement(By.xpath("//*[#value='Search'][#type='submit']"));
//phantomjs debug - Verify the button has been found
boolean buttonText = driver.findElement(By.xpath("//*[#value='Search'][#type='submit']")).isDisplayed();
System.out.println("buttonText Boolean is = "+buttonText);
//Click the Search button
//driver.findElement(By.xpath("//*[#value='Search'][#type='submit']")).sendKeys(Keys.RETURN);
//*********** This works in Selenium ***********
driver.findElement(By.xpath("//*[#value='Search'][#type='submit']")).click();
// Wait for the Choose Flights page to appear
int count = 1;
do
if (driver.getTitle().contains("Choose flights"))
{
break;
}
else
{
System.out.println("do loop iteration "+count+ " the title = "+ driver.getTitle());
Thread.sleep(1000);
count++;
}
while (count < 30);
System.out.println("After search the current page title is = "+ driver.getTitle());
Assert.assertTrue(driver.getTitle().contains("Choose flights"));
driver.quit();
}

I'm encountering a similar issue when using phantomjs via Jmeter (with WebDriver Sampler).
What I can see is that a modal exists on the page which is overlaying the fields I need to interact with. I can add assertions to verify the fields and buttons exists and capture their values, just cant click on the button.
The only workaround that I can think of is calling the function (button onclick function) although not my preference.

Related

Send keys not working , right xpath and id (Selenium)

Tried sendomg keys , right relative xpath or ID used but still not working properly
Tried using absolute xpath , relative xpath also ID. Tried using selassist and chropath still not working. Could there be something preventing it?
public void LoginWebSystem() {
driver = new ChromeDriver();
driver.get("http://localhost:82");
WebElement email = driver.findElement(By.id("login_username"));
email.sendKeys("superadmin");
System.out.println("Username Set");
WebElement password = driver.findElement(By.id("login_password"));
password.sendKeys("nelsoft121586");
System.out.println("Password Set");
WebElement login = driver.findElement(By.id("login_submit"));
login.click();
System.out.println("Login Button Clicked");
String newUrl = driver.getCurrentUrl();
if(newUrl.equalsIgnoreCase("http://localhost:82/controlpanel.php")){
System.out.println("Login Success");
}
else {
System.out.println("Login Failed");
}
driver.findElement(By.partialLinkText("Product")).click();
System.out.println("Successful in proceeding to Product Page");
driver.findElement(By.id("createlink")).click();
System.out.println("Successful in proceeding to Create Product by Detailed");
driver.switchTo().alert().accept();
System.out.println("Successful in clicking alert button");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
#Test (priority=1)
public void ProductDetails() {
WebElement product = driver.findElement(By.xpath(" //*[#id="text-product"]"));
product.sendKeys("superadmin");
}
}
Expected output should input superadmin to product textbox
You have a typo in your XPath expression:
WebElement product = driver.findElement(By.xpath(" //*[#id="text-product"]"));
^ remove this space break
It's better to use By.Id locator strategy where possible as this is the fastest and the most robust way of identifying elements in DOM
Consider using Explicit Wait to ensure that the element is present and can be interacted with as it might be the case the element becomes available after document.readyState becomes complete. Check out How to use Selenium to test web applications using AJAX technology article for more detailed explanation.
new WebDriverWait(driver, 10)
.until(ExpectedConditions.elementToBeClickable(By.id("text-product")))
.click();
Make sure that your selector matches an <input> because if the id belongs to other element type like <div> it doesn't make a lot of sense to send keys there.

Unable to click 2 value from the dropdown in webdriver

The Code is:
public void setRing(int index, String ringPattern) throws InterruptedException {
List<WebElement> webElementList = driver.findElements(By.xpath(an.getProperty("an_ringPattern")));
webElementList.get(index).click();
List<WebElement> options = webElementList.get(index).findElements(By.tagName("option"));
for (WebElement element : options) {
if (element.getText().equals(ringPattern)) {
element.click();
Thread.sleep(2000);
}
}
}
When I execute this code in debug mode, it is working fine. It selects whatever value I pass to the method.
But when I run this code it is not able to change the value in the drop down. It selects the value in the drop down, but it's not able to set the value.
Please let me know if I am missing something.
If the Exception .Error message display below at org.openqa.selenium.support.ui.WebDriverWait.timeoutExceptio‌​n(WebDriverWait.java‌​:80) is being thrown, means that somehow that element is not ready on the frame, the driver is not on that frame or the xpath is wrong.
You can try to switch to the frame where the element is located, like this: driver.switchToFrame("here goes the id of the frame"); You can inspect the ID of the frame or sometimes just passing the integer 0 works. Also, I would rather use wait1.until(ExpectedConditions.visibilityOfElementLocated(element)); instead of wait1.until(ExpectedConditions.presenceOfElementLocated(element));.
When you use presenceOfElementLocated, you cant assure that the element is visible for the driver.
You can use explicit wait in selenium - WebDriverWait
Use below modified code
public void setRing(int index, String ringPattern) throws InterruptedException {
List<WebElement> webElementList = driver.findElements(By.xpath(an.getProperty("an_ringPattern")));
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.presenceOfElementLocated(webElementList.get(index)));
webElementList.get(index).click();
List<WebElement> options = webElementList.get(index).findElements(By.tagName("option"));
for (WebElement element : options) {
WebDriverWait wait1 = new WebDriverWait(driver, 60);
wait1.until(ExpectedConditions.presenceOfElementLocated(element));
if (element.getText().equals(ringPattern)) {
element.click();
Thread.sleep(2000);
}
}
}

Getting Exception : Element not found in the cache - perhaps the page has changed since it was looked up

I am reaching to a page after clicking on a link.I have not clicking anything on that page yet. Still, As soon as the page loaded it throws an error:
Element not found in the cache - perhaps the page has changed since it was looked up
List<WebElement> securityGroup = driver.findElements(By.cssSelector("td[class='button-col']>a:nth-of-type(2)"));
System.out.println(securityGroup.size());
Thread.sleep(5000);
for(WebElement link:securityGroup) {
String b= link.getAttribute("href");
boolean a= b.contains(data0);
if(a){
System.out.println(b);
Thread.sleep(5000);
System.out.println("before clicking link");
link.click();
//After this new page opens and above error comes.**
}else {
System.out.println("No match found");
}
}
Thread.sleep(5000);
Select sel = new Select(driver.findElement(By.xpath("//select[#name='groupId']")));
System.out.println(sel.getOptions().toString());
sel.selectByValue("TEST");
This is because of the for loop.
You are finding the securityGroup which is a list and you are iterating through the list. In this for loop, you look for a condition and if yes you proceed to click on the link. But the issue here is that the list iteration is not complete and the for loop continues. But it wont find the String b= link.getAttribute("href"); of the next iteration because you are on a new page.
Use a break to break the loop once the condition is satisfied.
if(a){
System.out.println(b);
Thread.sleep(5000);
System.out.println("before clicking link");
link.click();
break;
}else {
System.out.println("No match found");
}
there is not enough time to load the page and take the element:
driver.findElement(By.xpath("//select[#name='groupId']"))
try to do ImplicitlyWait after you init the driver
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
and Thread.sleep(5000); is bad idea using with selenium, for waiting you have selenium methods
When you click on link and redirected to another page the driver looses securityGroup. That's what causing the exception.
You need to relocate securityGroup each itreation
List<WebElement> securityGroup = driver.findElements(By.cssSelector("td[class='button-col']>a:nth-of-type(2)"));
int size = securityGroup.size();
for (int i = 0 ; i < size ; ++i) {
securityGroup = driver.findElements(By.cssSelector("td[class='button-col']>a:nth-of-type(2)"));
WebElement link = securityGroup.get(i);
String b = link.getAttribute("href");
boolean a = b.contains(data0);
if(a) {
System.out.println(b);
Thread.sleep(5000);
System.out.println("before clicking link");
link.click();
}
else {
System.out.println("No match found");
}
}

wait on handler registering - selenium

There is a html page with button, and my selenium test is testing, that there is an action executed, when the button is clicked.
The problem is, that it looks like the click happens before the javascript is executed - before the handler is bound to the page. The consequence is, that the selenium test will click on the button, but no action happens.
I can solve this problem by repeatedly trying to click and then observe, if the desired action happened (some element is present on page, typically). I'd like to hear that there are some more elegant solutions...
There is no clear way to say "wait until element X has such-and-such handler"; this is a limitation of JavaScript and the DOM (see for example Get event listeners attached to node using addEventListener and jQuery find events handlers registered with an object), and for that matter a selenium Expected Condition can't be created, at least not trivially.
I've resorted to time.sleep(0.5).
You can write some logic to handle this.
I have write a method that will return the WebElement and this method will be called three times or you can increase the time and add a null check for WebElement
Here is an example
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("https://www.crowdanalytix.com/#home");
WebElement webElement = getWebElement(driver, "homekkkkkkkkkkkk");
int i = 1;
while (webElement == null && i < 4) {
webElement = getWebElement(driver, "homessssssssssss");
System.out.println("calling");
i++;
}
System.out.println(webElement.getTagName());
System.out.println("End");
driver.close();
}
public static WebElement getWebElement(WebDriver driver, String id) {
WebElement myDynamicElement = null;
try {
myDynamicElement = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By
.id(id)));
return myDynamicElement;
} catch (TimeoutException ex) {
return null;
}
}

selenium code to select radio button

Am doing automation tesing using selenium, i need help in regarding how to select radio button.If possible help me with selenium java code.
Assuming you have selenium set up its just:
selenium.click('radio button locator');
You may want to look at the selenium javadoc http://release.seleniumhq.org/selenium-remote-control/0.9.2/doc/java/com/thoughtworks/selenium/Selenium.html
click > xpath=(//input[#type='checkbox'])[position()=1]
click > xpath=(//input[#type='checkbox'])[position()=2]
click > xpath=(//input[#type='checkbox'])[position()=3]
click > xpath=(//input[#type='checkbox'])[position()=4]
etc ...
use this commands to select random and any radio button
public class radioExamJavaScr {
public static void main(String[] args) throws IOException {
WebDriver driver = new FirefoxDriver();
EventFiringWebDriver dr = new EventFiringWebDriver(driver);
dr.get("http://www.makemytrip.com/");
dr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
((JavascriptExecutor)dr).executeScript("document.getElementById('roundtrip_r').click();");
WebElement one_way = (WebElement)((JavascriptExecutor)dr).executeScript("return document.getElementById('oneway_r') ;");
System.out.println(one_way.isSelected());
WebElement round_trip = (WebElement)((JavascriptExecutor)dr).executeScript("return document.getElementById('roundtrip_r') ;");
System.out.println(round_trip.isSelected());
}
}
In the above example I am selecting radio button with "ROUND TRIP" using "JavaScript".
The last four lines are to verify and see whether the expected radio button is selected in the page or not.
NOTE: I am giving simple easy solution to solve a problem (selecting a radio) in the choosen webpage. A better code can be written. (user can write a method to accept radio ID and loop through all the existing radio button to see which one of them is selected).
I use this method:
String radioButtonId = "radioButtonId";
selenium.focus("id=" + radioButtonId);
selenium.click("id=" + radioButtonId, "concreteRadioButtonValue");
What you can do is this:
Create a method with a WebElement return type, and use the Method findElement(). Example:
WebDriver test;
test = new FirefoxDriver();
public static WebElement checkAndGet(By b) throws Exception {
return test.findElement(b);
}
Store the WebElement and use the Method click(). Example:
WebElement radiobutton = checkAndGet(By.xpath("//span[#class='label ng-binding']");
radiobutton.click();
Hope this helps!
Test Scenario : Select Gender(Female) radio button
Steps:
Launch new Browser
Open URL http://toolsqa.wpengine.com/automation-practice-form/
Select the Radio button (female) by Value ‘Female’
Code :
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver(); // Step 1 - Launch Browser
driver.get("http://toolsqa.com/automation-practice-form"); // Step 2 - Open Test URL
List<WebElement> rdBtn_Sex = driver.findElements(By.name("sex")); //
int size = rdBtn_Sex.size();
System.out.println("Total no of radio button :"+size);
for (int i=0; i< size; i++)
{
String sValue = rdBtn_Sex.get(i).getAttribute("value"); // Step 3 - 3. Select the Radio button (female) by Value ‘Female’
System.out.println("Radio button Name "+sValue);
if (sValue.equalsIgnoreCase("Female"))
{
rdBtn_Sex.get(i).click();
}
}
What you should do all the time is provide a locator for every object within a page and then use a method.
Like
driver.findElement(By.xpath(//CLASS[contains(., 'what you are looking for')])).click();