Unable to select from the drop-down option - java

Unable to select "Delhi" from the drop down option.....the x-path might be wrong...
public class spicejet {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\hp\\Desktop\\Colin\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("https://www.spicejet.com/");
driver.findElement(By.id("ctl00_mainContent_rbtnl_Trip_0")).click();
driver.findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
driver.findElement(By.xpath("//a[contains(#text,'Kochi')]")).click();
driver.findElement(By.id("ctl00_mainContent_ddl_destinationStation1_CTXT")).click();
List<WebElement> list=driver.findElements(By.xpath("//div[contains(#class,'dropdownDiv')]//ul//li//a"));
System.out.println(list.size());
for(int i=0; i<list.size(); i++) {
System.out.println(list.get(i).getText());
if(list.get(i).getText().contains("Delhi (DEL)"));{
list.get(i).click();
break;

Your xpath is correct. However there is terminator ; used with your if condition like if(list.get(i).getText().contains("Delhi (DEL)")); because of which the if condition is getting terminated and the first element from the list is getting selected from the line of code mentioned in the next line. You need to remove ; from the if condition and then it would work just fine.
Addition to that, you can also improve your xpath with the one i am mentioning below:
List<WebElement> list=driver.findElements(By.xpath("//div[#class='dropdownDiv']//li"));

Related

Selenium JS Executor Failure: "Failed to execute elementsFromPoint on Document"

I'm running code that fetches a span by the value of its text and then goes to rightclick it using this function:
public void rightClickElement(WebElement element) {
Actions action = new Actions(driver);
actions.contextClick(element).perform();
}
Basically I iterate over a list of filenames and select the element I want to manipulate by its filename by using the following XPATH:
//span[contains(text(), 'PLACEHOLDER')]
with a function that replaces PLACEHOLDER by the current value of the array of filenames I'm iterating over.
This is my code:
*Note: getAssertedElement is just a function I wrote that asserts an element's existence and returns it at the same time.
List<WebElement> textFilesElements = driver.findElements(By.xpath("//span[(#class='document') and contains(text(), '.txt')]"));
ArrayList<String> filesToDelete = new ArrayList<String>();
waitSeconds(1);
for (int i = 0; i < textFilesElements.size(); i++) {
filesToDelete.add(textFilesElements.get(i).getText());
}
for (int i = 0; i < filesToDelete.size(); i++) {
WebElement elementToDelete = getAssertedElement("Cannot find the current element",
replacePlaceholderInString(
"//span[contains(text(), 'PLACEHOLDER')]",
filesToDelete.get(i)
),
"xpath");
System.out.println("FICHIER TO DELETE" + elementToDelete.getText());
rightClickElement(elementToDelete);
// do things with element
...
}
This works fine the first time through the second for statement, but when I move on to the next filename, even though the element is visible and clickable, the test fails with the following error when it reaches the rightClickElement call:
javascript error: Failed to execute 'elementsFromPoint' on 'Document': The provided double value is non-finite.
I don't understand why, much less how to fix it.

how to google search using dynamic xpath?

I am trying to automate the Google Search for "Java" and when it provides a list, I want to select "java interview questions".
I tried using the below xpath, but the script is failing.
List<WebElement> list = driver.findElements(By.xpath("//ul[#role ='listbox']//li/descendent::div[#class='sbl1']"));
Below is my code for the same -
public class GoogleSearchTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver" , "C:/Users/User/Desktop/Selenium Drivers/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.name("q")).sendKeys("Java");
List<WebElement> list = driver.findElements(By.xpath("//ul[#role ='listbox']//li/descendent::div[#class='sbl1']"));
System.out.println("Total no of suggestions in search box::" +list.size());
for(int i=0; i<list.size();i++) {
System.out.println(list.get(i));
if(list.get(i).getText().contains("Java Tutorial")) {
list.get(i).click();
break;
}
}
}
}
I think you are using an invalid xpath locator and you need to give some delay before identifying & fetching the elements, try the below code :
driver.get("http://www.google.com");
driver.findElement(By.name("q")).sendKeys("Java");
Thread.sleep(1000);
List<WebElement> list = driver.findElements(By.xpath("//ul[#role ='listbox']//li"));
System.out.println("Total no of suggestions in search box :: " +list.size());
for(int i=0; i<list.size();i++) {
System.out.println(list.get(i));
if(list.get(i).getText().trim().contains("java interview questions") || list.get(i).getText().trim().equalsIgnoreCase("java interview questions")) {
list.get(i).click();
break;
}
}
Below is the screenshot which describes matching xpath:
No sure why you have to iterate through all the list items, when you can handle this with simple xpath. Here is the code that worked for me.
driver.get("http://www.google.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.findElement(By.name("q")).sendKeys("Java");
WebElement searchElement = driver.findElement(By.xpath("//div[#class='suggestions-inner-container']//span[.='java salon']"));
System.out.println(searchElement.getText());
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();",searchElement);
Thread.sleep(1000); // just added time to make sure you will see the page navigation is successful.
driver.quit();
simple. You have spelling mistake in the xpath. Its descendant and not descendant.
//ul[#role='listbox']//li/descendant::div[#class='sbtc']
Use Chropath, its shows you when the xpath is invalid
That xpath appears to be invalid. I think it would be easiest to find the elements by css using their class, like this:
List<WebElement> list = driver.findElements(By.cssSelector('li.sbct'));

Getting StaleElementReferenceException while trying print the link names

I'm trying to print first 5 pages links displayed in google search.. But getting StateElementReferenceException Not sure which one went wrong..
public class GoogleCoInTest {
static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver", "D:\\bala back up\\personel\\selenium\\Jars\\Drivers\\geckodriver.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.google.co.in/");
//driver.findElement(By.xpath("//input[class='gsfi']")).sendKeys("Banduchode");;
WebElement search=driver.findElement(By.cssSelector("input#lst-ib"));
search.sendKeys("Banduchode");
search.sendKeys(Keys.ENTER);
printLinksName();
List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[#id='nav']/tbody/tr/td/a"));
for(int i=0;i<5;i++){
System.out.println(fiveLinks.get(i).getText());
fiveLinks.get(i).click();
Thread.sleep(5000);
printLinksName();
}
}
public static void printLinksName() throws InterruptedException{
List<WebElement> allLinks=driver.findElements(By.xpath("//*[#id='rso']/div/div/div/div/div/h3/a"));
System.out.println(allLinks.size());
//print all list
for(int i=0;i<allLinks.size();i++){
System.out.println("Sno"+(i+1)+":"+allLinks.get(i).getText());
}
}
}
it prints fine till 2nd page , but there after I am getting
Exception in thread "main" org.openqa.selenium.StaleElementReferenceException: The element reference of <a class="fl"> stale: either the element is no longer attached to the DOM or the page has been refreshed
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
A couple of things:
Your script prints the result from the first 2 pages as expected.
When you call printLinksName() for the first time it works.
Next, you are storing the 10 PageNumbers in a Generic List of type WebElement.
First time within the for() loop you are clicking on the WebElement of Page 2 and then printing all the links by calling printLinksName().
While you are in the second iteration within for() loop, the reference of List<WebElement> fiveLinks is lost as the DOM have changed. Hence, you see StaleElementReferenceException.
Solution
A simple solution to avoid StaleElementReferenceException would be to move the line of code List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[#id='nav']/tbody/tr/td/a")); with in the for() loop. So your code block will look like:
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Q44970712_stale
{
static WebDriver driver = null;
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.google.co.in/");
//driver.findElement(By.xpath("//input[class='gsfi']")).sendKeys("Banduchode");;
WebElement search=driver.findElement(By.cssSelector("input#lst-ib"));
search.sendKeys("Banduchode");
search.sendKeys(Keys.ENTER);
printLinksName();
for(int i=0;i<5;i++)
{
List<WebElement> fiveLinks=driver.findElements(By.xpath(".//*[#id='nav']/tbody/tr/td/a"));
System.out.println(fiveLinks.get(i).getText());
fiveLinks.get(i).click();
Thread.sleep(5000);
printLinksName();
}
}
public static void printLinksName() throws InterruptedException
{
List<WebElement> allLinks=driver.findElements(By.xpath("//*[#id='rso']/div/div/div/div/div/h3/a"));
System.out.println(allLinks.size());
//print all list
for(int i=0;i<allLinks.size();i++)
{
System.out.println("Sno"+(i+1)+":"+allLinks.get(i).getText());
}
}
}
Note: In this simple solution when you finish printing the second page, next when you will create List<WebElement> fiveLinks through xpath with .//*[#id='nav']/tbody/tr/td/a for second time, Page 1 is the first element which gets stored in the fiveLinks List. Hence you may be again redirected to Page 1. To avoid that you may consider to take help of xpath with proper indexing.
your script is trying to click on each link from the first page, which brings you to a new page. once it completes work on that page, it doesn't seem to return to the first page, so the script can't find the next link in your list.
even if it did return to the first page, you would still have a stale element because the page has been reloaded. You'll need to keep track of the links in the first page by something else (like the href maybe?), and find the link again by that identifier before you click on it.
This is due to referencing object after moving to another page. please try to add the following lines inside the for loops at the end. It may resolve stale reference issue.
driver.navigate().back();
fiveLinks=driver.findElements(By.xpath(".//*[#id='nav']/tbody/tr/td/a"));

Selenium: StaleElementReferenceException

I've been researching this error for a while and have tried many things and nothing seems to work...
while(!driver.findElements(By.className("next")).isEmpty()) {
//elements = driver.findElements(By.xpath("//a[#class='name']"));
elements = findDynamicElements("//a[#class='name']");
for (WebElement e : elements) {
userName = e.getText(); //<--EXCEPTION HERE
check_visitor_profile(userName);//<--WE LEAVE THE PAGE HERE
Thread.sleep(3000); //<--NO TRY/CATCH BLOCK FOR READABILITY
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
elements = findDynamicElements("//a[#class='name']");
}
driver.findElement(By.xpath("VisitsNext")).click();
}
protected List<WebElement> findDynamicElements(String path) {
List<WebElement> result;
String xPath = path;
new WebDriverWait(driver, 25).until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(xPath)));
//new WebDriverWait(driver, 25).until(elementIdentified(By.id(path)));
try {
result = driver.findElements(By.xpath(xPath));
return result;
}
catch(WebDriverException e) {
return null;
}
);
}
My code craps out on the first line of the for loop where userName is assigned. I've seen on this forum that you should use 'presenceOfElementLocated' and explicitly wait for the element to come back but that doesn't work either. I used 'presenceOfAllElementsLocatedBy' for a list but I have a method that uses 'presenceOfElementLocated' which doesn't work either.
I know stuff like the Thread.sleep and the implicitlyWait line is probably unnecessary at this point but I've literally tried everything and it doesn't work...
The error occurs because when I call 'check_visitor_profile' it leaves the page - when it comes back the elements are out of place so I have to find them again. Which I do but it still throws the exception.
Any Ideas?
Thanks.
The problem might occur because you are changing elements in the middle of the loop. It will cause you trouble even without the StaleElementReferenceException. Use a for loop instead of the for each loop
elements = findDynamicElements("//a[#class='name']");
int size = elements.size();
for (int i = 0 ; i < size ; ++i) {
elements = findDynamicElements("//a[#class='name']");
userName = elements.get(i).getText();
check_visitor_profile(userName);
}
Handle the exception explicitly as the element is no longer attached to the DOM or has changed at that moment you call "check_visitor_profile"
See the link below might help
catch(StateElementException e){
System.out.println("StaleElement dealt with since you successfully left page ");
}
http://docs.seleniumhq.org/exceptions/stale_element_reference.jsp

selenium dynamically click li item

I am trying to dynamically search an "li" tag item and double-click on this website: www.jstree.com (the right-top hierarchy tree sample). The code does find the WebElement but does not do anything. I am trying as follows. Can someone please point to what I am doing wrong? I am using Firefox 35.0.1 and selenium 2.44.0.
driver.get(baseUrl + "http://www.jstree.com/");
WebElement we = driver.findElement(By.xpath("/html/body/div/div/div[1]/div[1]/div[2]/div[1]/ul/li[1]/ul"));
Actions action = new Actions(driver);
List<WebElement> liItems = we.findElements(By.tagName("li"));
for(WebElement liItem:liItems)
{
System.out.println(liItem.getText());
if(liItem.getText().startsWith("initially open"))
{
System.out.println("Found it...");
liItem.click();
action.moveToElement(liItem).doubleClick().build().perform();
break;
}
}
I ended up doing this:
Modified the selector to make sure ONLY the expected elements are returned. It helps a lot in terms of execution time and reducing the number of unwanted loopings. And, then find the element in run time and use Action() on that to perform double click. I also update the Selenium binding as #alecxe suggested to work with latest Firefox
public void DemoTest() throws InterruptedException {
List<WebElement> liItems = driver.findElements(By.xpath("//*[contains(text(),'initially open')]"));
for(WebElement liItem:liItems)
{
Actions actions = new Actions(driver);
actions.moveToElement(liItem).doubleClick().build().perform();
}
}

Categories