How can I verifying a footer text using selenium Junit - selenium

I want to verify a text in the footer. I normally copied the XPath locator and find element then get the text of the element, but nothing happens for this code part in Junit.
From this website I need to get the footer text:
https://www.qaagility.com/
Here is the code I am using for this. I know there is another way of doing it.
public class QAA_mock3 {
private WebDriver driver;
private Map<String, Object> vars;
JavascriptExecutor js;
#Before
public void setUp() {
driver = utils.HelperFunctions.createAppropriateDriver("Chrome");
js = (JavascriptExecutor) driver;
vars = new HashMap<String, Object>();
}
#Test
public void test() {
String ExpTitle = "QAAgility" ;
Actions actions = new Actions(driver);
By TwitterLink = By.xpath("//*[#id=\"custom_html-4\"]/div/div[1]/a[2]");
By footer = By.xpath("//div[#id='footer']");
By imglogo = By.cssSelector("img.header-image");
driver.get(" https://www.qaagility.com");
System.out.println("Loaded page...");
String ActTitle = driver.getTitle();
System.out.println("page Title..."+ ActTitle);
if(ActTitle.contains(ExpTitle)) {
System.out.println("Verified the title for ..."+ ExpTitle);
}
else
System.out.println("Title verification went wrong...");
WebElement imgSize = driver.findElement(imglogo);
Dimension imageSize = imgSize.getSize();
int Height = imageSize.getHeight();
int Width = imageSize.getWidth();
System.out.println("The size of the Logo is : Width = "+ Width + "; Height = "+Height);
WebElement Twitter = driver.findElement(TwitterLink);
String Href = Twitter.getAttribute("href");
System.out.println("Twitter Link is :"+ Href);
WebElement footerText = driver.findElement(footer);
System.out.println("WebElement for footer is"+ footerText);
actions.moveToElement(footerText).build().perform();
String FTText = footerText.getText();
System.out.println("Footer Text is :"+ FTText);
}
#After
public void tearDown() throws Exception {
driver.quit();
}
}

You wrong define footer locator:
By footer = By.xpath("//div[#id='footer']");
Try this:
By footer = By.className("copyright-bar")

Related

The button in date picker is getting clicked more than the number of clicks needed [duplicate]

I am trying to select a "Depart date" as of 31st october 2018 from the calender https://spicejet.com/ But I am getting error "unknown error: Element is not clickable at point (832, 242). Other element would receive the click: ..." Please help me out. Here is my code getting such exception:
public class bookflight extends Thread {
UtilityMethods utilObj= new UtilityMethods();
#Test
public void SighnUp() throws IOException
{
utilObj.getdriver().get("https://spicejet.com");
utilObj.getdriver().manage().window().maximize();
utilObj.getdriver().findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
utilObj.getdriver().findElement(By.xpath("//a[contains(text(),'Guwahati (GAU)')]")).click();
utilObj.getdriver().findElement(By.xpath("//a[contains(text(),'Goa (GOI)')]")).click();
utilObj.getdriver().findElement(By.className("ui-datepicker-trigger")).click();
utilObj.getdriver().findElement(By.xpath("//div[#class='ui-datepicker-group ui-datepicker-group-first'])/parent:://table[#class='ui-datepicker-calendar']following-sibling::./a/contains(text(),'31')")).click();
}
}
To select From (e.g. Guwahati(GAU)), To (e.g. Goa(GOI)) destination and DEPART DATE as 31/10 within the url https://spicejet.com/ you need to induce WebDriverWait for the desired element to be clickable and you can use the following solution:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class spicejet_login {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://spicejet.com");
new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#id='ctl00_mainContent_ddl_originStation1_CTXT']"))).click();
driver.findElement(By.xpath("//div[#id='glsctl00_mainContent_ddl_originStation1_CTNR']//table[#id='citydropdown']//li/a[#value='GAU']")).click();
driver.findElement(By.xpath("//div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//table[#id='citydropdown']//li/a[#value='GOI']")).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//table[#class='ui-datepicker-calendar']//tr//a[contains(#class,'ui-state-default') and contains(.,'31')]"))).click();
}
}
Browser Snapshot:
There is lots of different factors which results into this exception,
i like to suggest you to try putting some wait.
WebDriverWait wait = new WebDriverWait(utilObj.getdriver(), 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("ctl00_mainContent_ddl_originStation1_CTXT")));
then try clicking element,
utilObj.getdriver().findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
You can click on element by Action class, based on Exception type:
Actions action = new Actions(driver);
action.moveToElement(WebElement to click).click().perform();
Updated answer to click next date.
//div[contains(#class, 'ui-datepicker-group-first')]//td[#data-month='9' and #data-year='2018']/a[.=31]
You can modify the above XPATH to select date based on YEAR/MONTH/DATE. for more XPath creation go-through my answers.
var path ="//div[contains(#class, 'ui-datepicker-group-first')]//td[#data-month='9' and #data-year='2018']/a[.=31]";
var elem = document.evaluate(path, window.document, null, 9, null ).singleNodeValue;
console.log( elem );
elem.click();
When you enter FROM and TO data, then DEPART DATE field get auto selected. So, just you need to select the first data using javascript.
FROM « //div[#id='ctl00_mainContent_ddl_originStation1_CTNR']//a[#text='Guwahati (GAU)']
TO « //div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//a[#text='Goa (GOI)']
DEPART DATE «
//div[contains(#class, 'ui-datepicker-group-first')]//a[contains(#class, 'ui-state-active')]
sample test program.
import io.github.yash777.driver.Browser;
import io.github.yash777.driver.Drivers;
import io.github.yash777.driver.WebDriverException;
public class SpiceJET {
static WebDriver driver;
static WebDriverWait explicitWait;
public static void main(String[] args) throws WebDriverException, IOException {
test();
}
public static void test() throws WebDriverException, IOException {
Drivers drivers = new Drivers();
String driverPath = drivers.getDriverPath(Browser.CHROME, 63, "");
System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
driver = new ChromeDriver( capabilities );
explicitWait = new WebDriverWait(driver, 10);
//Maximize browser window
driver.manage().window().maximize();
//Go to URL which you want to navigate
driver.get("https://spicejet.com/");
clickElement("//input[#id='ctl00_mainContent_ddl_originStation1_CTXT'][1]");
clickElement("//div[#id='ctl00_mainContent_ddl_originStation1_CTNR']//a[#text='Guwahati (GAU)']");
clickElement("//input[#id='ctl00_mainContent_ddl_destinationStation1_CTXT'][1]");
clickElement("//div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//a[#text='Goa (GOI)']");
clickUsingJavaScript("//div[contains(#class, 'ui-datepicker-group-first')]//a[contains(#class, 'ui-state-active')]");
}
}
public static void clickElement(String locator) {
By findBy = By.xpath( locator );
WebElement element = explicitWait.until(ExpectedConditions.elementToBeClickable( findBy ));
element.click();
}
public static void clickUsingJavaScript( String locator ) {
StringBuffer click = new StringBuffer();
click.append("var elem = document.evaluate(\""+locator+"\", window.document, null, 9, null ).singleNodeValue;");
click.append("elem.click();");
System.out.println("JavaScript Click.");
jse.executeScript( click.toString() );
}
For Automatic management of Selenium Driver Executable’s in run-time for Java use SeleniumWebDrivers
NOTE: If you are selecting DEPART DATE which got auto selected then selenium throws exception
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error:
Element <input type="text" readonly="readonly" id="ctl00_mainContent_view_date2" class="custom_date_pic required home-date-pick">
is not clickable at point (784, 241). Other element would receive the click: <span class="ui-datepicker-month">...</span>
I hope below code is helpful and handle departure and return date
public class SpicejetDropdowns1 {
public static void main(String[] args) throws InterruptedException
{ System.setProperty("webdriver.chrome.driver","E:\\ChromeDriver\\ChromeDriver2.46\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.spicejet.com/");
driver.manage().window().maximize();
System.out.println(driver.getTitle()); driver.findElement(By.cssSelector("#ctl00_mainContent_rbtnl_Trip_1")).click();
// OriginStation
driver.findElement(By.xpath(".//*[#id='ctl00_mainContent_ddl_originStation1_CTXT']")).click();
driver.findElement(By.cssSelector("a[value='DEL']")).click();
// Destination
driver.findElement(By.xpath(".//*[#id='ctl00_mainContent_ddl_destinationStation1_CTXT']")).click();
driver.findElement(By.xpath("(//a[#value='HYD'])[2]")).click();
Thread.sleep(3000); driver.findElement(By.xpath("//input[#id='ctl00_mainContent_view_date1']")).click();
if(driver.findElement(By.id("Div1")).getAttribute("style").contains("1"))
{
System.out.println("its enabled");
Assert.assertTrue(true);
}
else
{
Assert.assertTrue(false);
}
while(!driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText().contains("October"))
{
// driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click();
driver.findElement(By.xpath("//a[#class='ui-datepicker-next ui-corner-all']/span[#class='ui-icon ui-icon-circle-triangle-e']")).click();
System.out.println(driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText());
}
List<WebElement> dates= driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td"));
int count= dates.size();
for(int i=0; i<count; i++)
{
String txt = driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).getText();
if(txt.equalsIgnoreCase("28"))
{
driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).click();
System.out.println(txt);
break;
}
}
// Return Date Selection
Thread.sleep(3000); driver.findElement(By.xpath("//input[#id='ctl00_mainContent_view_date2']")).click();
while(!driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText().contains("October"))
{
// driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click();
driver.findElement(By.xpath("//a[#class='ui-datepicker-next ui-corner-all']/span[#class='ui-icon ui-icon-circle-triangle-e']")).click();
System.out.println(driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText());
}
List<WebElement> MDates= driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td"));
int Mcount= dates.size();
for(int i=0; i<Mcount; i++)
{
String txt = driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).getText();
if(txt.equalsIgnoreCase("31"))
{
driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).click();
System.out.println(txt);
break;
}
}
//Select Passengers
Thread.sleep(4000);
driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).click();
Thread.sleep(4000);
WebElement Adults = driver.findElement(By.xpath("//select[#id='ctl00_mainContent_ddl_Adult']")); Select adultsdrp = new Select(Adults);
adultsdrp.selectByValue("2");
WebElement childs = driver.findElement(By.xpath("//select[#id='ctl00_mainContent_ddl_Child']"));
Select childsdrp = new Select(childs);
childsdrp.selectByValue("2");
driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).click();
System.out.println(driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).getText());
//Static Currency Dropdown
WebElement Currency = driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency"));
Select currencydrp = new Select(Currency);
currencydrp.selectByValue("USD"); Assert.assertEquals(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")).getAttribute("value"), "USD"); System.out.println(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")).getAttribute("value"));
}
}

Why my selenium function say no Element found

Why if i use same code of affordabilityErrorVerify() in mortgageCalculator() function its working fine but when i use that code in affordabilityErrorVerify() [ same as i posted here ] it says : --> org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"#ifrm_13536"}
its weird for me can someone help me how i can make it work
public class test1 extends base {
public WebDriver driver;
public static Logger log =LogManager.getLogger(base.class.getName());
#BeforeTest
public void initialize() throws IOException {
driver = initializeDriver(); // initialize the browser driver based on data.properties file browser value
}
#Test(dataProvider = "dataDriven")
public void mortgageCalculator(String amount, String year, String Frequency, String type, String product,
String term, String rate) throws IOException, InterruptedException {
driver.get(prop.getProperty("url")); // read the data.properties file for get the value of url
driver.manage().window().maximize();
LandingPage l = new LandingPage(driver); // created object for Landing page to access page element
Actions actions = new Actions(driver);
WebElement mainMenu = l.menuBar();
actions.moveToElement(mainMenu);
WebElement subMenu = l.clickLink();
actions.moveToElement(subMenu);
actions.click().build().perform();
// Explicit wait because calculator is in frame and it loads after some time
// so wait until frame is visible
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#class,'col-12 col-md-9 side-content')]")));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(0,500)");
// switch to frame elements
driver.switchTo().frame(l.switchToFrame());
Thread.sleep(3000);
l.productTabClick().click(); // click on product tab
Thread.sleep(3000);
WebElement money = l.mortgageAmount();
money.click();
money.sendKeys(Keys.CONTROL + "a");
money.sendKeys(Keys.DELETE);
money.sendKeys(amount);
WebElement period = l.mortgageYear();
period.click();
period.sendKeys(Keys.CONTROL + "a");
period.sendKeys(Keys.DELETE);
period.sendKeys(year);
Select s = new Select(l.paymentFrequency());
s.selectByValue(Frequency);
// if data provider send Fixed it will click on fixed radio button otherwise click on variable
if (type == "Fixed") {
l.paymentType().click();
} else {
l.paymentType().click();
}
Select ss = new Select(l.paymentProduct());
ss.selectByValue(product);
Thread.sleep(3000);
driver.switchTo().defaultContent();
js.executeScript("window.scrollBy(0,300)");
driver.switchTo().frame(l.switchToFrame());
Thread.sleep(3000);
WebElement inputOwnRateTerm = l.paymentTerm();
inputOwnRateTerm.click();
inputOwnRateTerm.sendKeys(Keys.CONTROL + "a");
inputOwnRateTerm.sendKeys(Keys.DELETE);
l.paymentTerm().sendKeys(term);
WebElement inputOwnRateValue = l.paymentRate();
inputOwnRateValue.click();
inputOwnRateValue.sendKeys(Keys.CONTROL + "a");
inputOwnRateValue.sendKeys(Keys.DELETE);
l.paymentRate().sendKeys(rate);
inputOwnRateValue.sendKeys(Keys.ENTER);
Thread.sleep(3000);
String actualPayment = l.monthlyPayment().getText();
String actualIOT = l.interestOverTerm().getText();
String actualInterestOverTerm = actualIOT.substring(0, actualIOT.length()-1);
//double actualInterestOverTerm = Math.round(actualIOT)* 10.0) / 10.0;
//System.out.print(actualPayment); // uncomment to see what Mortgage Payment amount function is returning for given data
//System.out.print(actualInterestOverTerm);
//System.out.print(actualIOT);
String totalAmount = amount;
int arg1 = Integer.parseInt(totalAmount);
String mortgageRate = rate;
double arg2 = Double.parseDouble(mortgageRate);
String totalYear = year;
int arg3 = Integer.parseInt(totalYear);
// to find out total Interest over term months based on year
String iot = term;
int iot1 = Integer.parseInt(iot);
int arg4 = iot1 * 12;
// Pass all 4 argument into mortgage calculator to assert actual and expected result
calculator c = new calculator();
double[] expected = c.mortgageCalculator(arg1, arg2, arg3, arg4);
//System.out.println("Mortgage Payment :" + expected[0]); // giving back Mortgage Payment amount from custom function
//System.out.println("Interest over term :" + expected[1]); // giving back Interest over term amount from custom function
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(); // converting numbers into money format [number format]
String act = defaultFormat.format(expected[1]);
String expectedInterestOverTerm = act.substring(0, act.length()-1);
//***********************
// ActualPayment = Getting value from https://www.coastcapitalsavings.com/calculators/mortgage-calculator
// Expected[0] = Getting value from calculator() function which is mortgageCalculator logic file
//***********************
Assert.assertEquals(actualPayment,defaultFormat.format(expected[0])); // Assertion to find out both values are same
Assert.assertEquals(actualInterestOverTerm,expectedInterestOverTerm); // Assertion to find out both values are same
log.info("*************Expected****************");
log.info("Mortgage Payment :" + expected[0]);
log.info("Interest Over Term :" + expectedInterestOverTerm);
log.info("**************Actual*****************");
log.info("Mortgage Payment :" + actualPayment);
log.info("Interest Over Term :" + actualInterestOverTerm);
log.info("_______________________________________");
}
#Test
public void affordabilityErrorVerify() throws InterruptedException
{
LandingPage l = new LandingPage(driver); // created object for Landing page to access page element
JavascriptExecutor js = (JavascriptExecutor) driver;
Thread.sleep(3000);
driver.switchTo().defaultContent();
js.executeScript("window.scrollBy(0,-500)");
Thread.sleep(3000);
driver.switchTo().frame(l.switchToFrame());
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#class,'col-12 col-md-9 side-content')]")));
Thread.sleep(3000);
l.affordabilityTabClick().click(); // click on affordability tab
Thread.sleep(3000);
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).click();
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).sendKeys("10000");
driver.findElement(By.cssSelector("slider-control:nth-child(3) > #slider-container #name")).sendKeys(Keys.ENTER);
}
By looking at your code, I have a probable solution to your problem.
There is no priority defined for tests. So in TestNG, if priority is not defined, the test will get executed in alphabetical order. In this case, affordabilityErrorVerify() test will execute first and then mortgageCalculator().
If I observe affordabilityErrorVerify(), there is no method to open URL like driver.get(url) so no page will get open and it will cause NoSuchElementException
A possible answer can be assigned priority to tests
#Test (priority=1, dataProvider = "dataDriven")
public void mortgageCalculator(String amount, String year, String Frequency, String type, String product,
String term, String rate) throws IOException, InterruptedException {
//code
}
#Test (priority=2)
public void affordabilityErrorVerify() throws InterruptedException
{
//code
}
In this as well you have to make sure actions on second test are continuing on same page where test1 ends.
Modify your tests and actions considering flow of test and it will work
Happy coding~

Stale Element reference error on finding the element -> when navigates back to previous page

My WebDriver script is simply finding elements on the page 1(Product display page) and clicking on 1st element to see if its working, then navigates back to Product display page.
It throws Stale Element Reference error and does not click the second element on the page, says element is not attached to the page.
Code is :
public class EcommerceSearchResult {
public static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://store.demoqa.com/");
WebElement searchBox = driver.findElement(By.xpath("//input[contains(#class,'search')]"));
searchBox.sendKeys("iphone"+"\n");
List<WebElement> gridrow
= driver.findElements
(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
int count = gridrow.size();
System.out.print(count);
for(int i = 0 ; i<count ; i++)
{
List<WebElement> listingelementinloop = driver.findElements(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
System.out.println(gridrow.get(i).getText());
listingelementinloop.get(i).click();
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
}
}
In the loop you need to replace following line:
System.out.println(gridrow.get(i).getText());
With
System.out.println(listingelementinloop.get(i).getText());
As, elements in the gridrow list will become stale once you click on 'Back' button of browser.
Alternatively, following is another way of performing the same task:
public static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://store.demoqa.com/");
WebElement searchBox = driver.findElement(By.xpath("//input[contains(#class,'search')]"));
searchBox.sendKeys("iphone"+"\n");
List<WebElement> gridrow
= driver.findElements
(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
int count = gridrow.size();
System.out.print(count);
for(int i = 1 ; i<=count ; i++)
{
WebElement element =
driver.findElement(By.xpath(".//*[#id='grid_view_products_page_container']/div/div[" + i + "]"));
System.out.println(element.getText());
element.click();
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
}
}
Let me know, if you have any further queries.
The problem is that you are looping through a collection of elements that you collected from the page. Once you leave that page or reload it, the element references you were storing become stale, thus the error. One way to get around this is to use an index into the collection and loop over that. I've rewritten your code to make use of functions to take care of repeated actions. I've tested this code and it works.
Part of main
driver.get("http://store.demoqa.com/");
Search("iphone");
for (int i = 0; i < GetProductCount(); i++)
{
ClickProduct(i);
driver.navigate().back();
}
and supporting functions
public void Search(String searchTerm)
{
driver.findElement(By.cssSelector("input[value='Search Products']")).sendKeys(searchTerm + "\n");
}
public void ClickProduct(int index)
{
driver.findElements(By.cssSelector("h2 > a")).get(index).click();
}
public int GetProductCount()
{
return driver.findElements(By.cssSelector("h2 > a")).size();
}
Below is the solution code for your problem.Tested it in my machine and attached console screenshot.
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class EcommerceSearchResult {
public static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://store.demoqa.com/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement searchBox = driver.findElement(By.xpath("//input[contains(#class,'search')]"));
searchBox.sendKeys("iphone"+"\n");
List<WebElement> gridrow = driver.findElements(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
int count = gridrow.size();
System.out.print(count+"\n");
for(int i = 0 ; i<count ; i++)
{
WebElement listingelementinloop = driver.findElement(By.xpath(".//*[#id='grid_view_products_page_container']/div/div["+(i+1)+"]"));
System.out.println(listingelementinloop.getText());
listingelementinloop.findElement(By.xpath(".//div/a")).click();
wait.until(ExpectedConditions.urlContains("products-page/product-category"));
driver.navigate().back();
wait.until(ExpectedConditions.titleIs("iphone | Search Results | ONLINE STORE"));
}
}
}

Unable to find the locator with Link Text test case getting failed

I am not able find the locator with anchor tag. Using xpath doesn't give the result.
Here is the HTML code :
<a id="sme1" class="item" href="/website-url" onclick="swapClasses('sme1')"
target="main" style="background-color:
transparent;">Mailboxes</a>
Selenium code :
private static final String baseURL = "http://10.112.75.248/";
private static final String adminURL = baseURL + "manager/";
private static String username = "admin";
private static String password = "default";
WebDriver driver ;
SearchElement searchEl;
#BeforeTest
public void setBaseURL(){
driver = new FirefoxDriver();
driver.get(adminURL);
searchEl = new SearchElement();
}
#Test(priority=0)
public void verifyLoginSuccessFull() {
searchEl.getElementsByXpath(driver, "//input[#name='username']").sendKeys(username);
searchEl.getElementsByXpath(driver, "//input[#name='password']").sendKeys(password);
searchEl.getElementsByXpath(driver, "//input[#name='submit']").submit();
String expected = "Selenium Home Page";
Assert.assertEquals(driver.getTitle(), expected);
}
#Test(priority=1)
public void addMailbox(){
//WebDriverWait wait = new WebDriverWait(driver, 1000);
//wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='Mailboxes']")));
//driver.findElement(By.id("smel")).click();
searchEl.getElementsByLinkText(driver, "//a[text()='Mailboxes']").click(); //This line of code not fetching the locator.
}
SearchElement class used as a controller :
public class SearchElement {
public WebElement getElementsByXpath(WebDriver driver,String locator){
WebElement el = driver.findElement(By.xpath(locator));
return el;
}
public WebElement getElementsByLinkText(WebDriver driver,String locator){
WebElement el = driver.findElement(By.linkText(locator));
return el;
}
}
Actual Error :
Unable to locate element: {"method":"link
text","selector":"//a[text()='Mailboxes']"}
Note : The URL is different when the user logs in and when the user is presented the login page. I dont know it might be a problem.
Please help in advance.
By.linkText() method expects link text as parameter, but in that code you're passing XPath string. Try to pass the link text instead :
searchEl.getElementsByLinkText(driver, "Mailboxes").click();
try this.
//a[.='Mailboxes']
This is a text base search and "." inside the xpath navigates you to the parent

Unable to control slider captcha jquery using Selenium Webdrive?

I want to record slider captcha given on our client site.
We have get this concept from other site named as http://www.fmylife.com/signup
This have slider captcha for registration
I have try to use selenium webdriver action builder
public class TestFmylife {
WebDriver driver;
Selenium selenium;
#BeforeMethod
public void startSelenium() {
driver = new FirefoxDriver();
selenium = new WebDriverBackedSelenium(driver, "http://www.fmylife.com/");
driver.manage().window().maximize();
}
#AfterMethod
public void stopSelenium() {
driver.close();
}
#Test
public void testFmylife() {
selenium.open("/");
selenium.click("link=Sign up");
selenium.waitForPageToLoad("30000");
selenium.type("name=login", "testfmylife");
selenium.type("name=pass", "123#fmylife");
selenium.type("name=passc", "123#fmylife");
selenium.type("name=mail", "testfmylife#gmail.com");
Point MyPoint= driver.findElement(By.xpath("//*[#id='bgSlider']")).getLocation();
WebElement someElement = driver.findElement(By.xpath("//*[#id='bgSlider']"));
System.out.println(MyPoint.x+"--------"+MyPoint.y);
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement).moveByOffset(MyPoint.x,(MyPoint.y + 100)).release().build();
dragAndDrop.perform();
selenium.click("css=div.form > div.ok > input[type=\"submit\"]");
}
}
But I can't move slider using this code
Help me to sort this out
I used the dragAndDropBy method of the Actions class (java.lang.Object
org.openqa.selenium.interactions.Actions) and moved the slider by 200 points horizontally . Please give the following code a try:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.fmylife.com/signup");
WebElement slider = driver.findElement(By.xpath(".//*[#id='Slider']"));
Actions builder = new Actions (driver);
builder.dragAndDropBy(slider, 200, 0).build().perform();
Actions builder = new Actions(driver);
Action dragAndDrop = builder.clickAndHold(someElement)
.moveToElement(otherElement)
.release(otherElement)
.build();
dragAndDrop.perform();
more can be found at - http://code.google.com/p/selenium/wiki/AdvancedUserInteractions
You can use locator as follows -
String xto=Integer.toString(LocatorTo.getLocation().x);
String yto=Integer.toString(LocatorTo.getLocation().y);
Working code-
WebDriver driver = new InternetExplorerDriver();
driver.get("http://jqueryui.com/demos/slider/");
//Identify WebElement
WebElement slider = driver.findElement(By.xpath("//div[#id='slider']/a"));
//Using Action Class
Actions move = new Actions(driver);
Action action = move.dragAndDropBy(slider, 30, 0).build();
action.perform();
driver.quit();
Source - https://gist.github.com/2497551
If your slider is like mine
with a "slider handle" (an <a/> tag as the box with the value "5ft 5") within a "slider track" (a <div> tag as the long black bar) then the following code will in C# will work to move the slider handle a percentage along the slider track.
public void SetSliderPercentage(string sliderHandleXpath, string sliderTrackXpath, int percentage)
{
var sliderHandle = driver.FindElement(By.XPath(sliderHandleXpath));
var sliderTrack = driver.FindElement(By.XPath(sliderTrackXpath));
var width = int.Parse(sliderTrack.GetCssValue("width").Replace("px", ""));
var dx = (int)(percentage / 100.0 * width);
new Actions(driver)
.DragAndDropToOffset(sliderHandle, dx, 0)
.Build()
.Perform();
}