Tips for managing the second datepicker for the return journey on Abhibus using Selenium webdriver

I am currently working on a code to choose departure date and return journey date, but I am encountering an issue where the return journey date is not being selected. The driver seems to be skipping over the return date selection and proceeding directly to the search button without entering a return date.

public class Callender {
    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\selenium\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.get("https://www.abhibus.com/");
        //to select leaving from
        WebElement source =driver.findElement(By.xpath("//*[@id='source']"));
        source.clear();
        source.sendKeys("Tenal");
        Thread.sleep(2000);
        source.sendKeys(Keys.ENTER);
        //to select destination
        WebElement destination =driver.findElement(By.xpath("//*[@id='destination']"));
        destination.clear();
        destination.sendKeys("Hyderaba");
        Thread.sleep(2000);
        destination.sendKeys(Keys.ENTER);


        WebElement element = driver.findElement(By.xpath("//*[@id=\"datepicker1\"]"));
        String journeydate="04-10-2019";
        selectJourney(driver,element,journeydate);

        Thread.sleep(3000);
        WebElement element1 = driver.findElement(By.xpath("//*[@id=\"datepicker2\"]"));
        String returndate="06-10-2019";
        selectRJourney(driver,element1,returndate);
        //to click search button
        driver.findElement(By.xpath("//*[@id=\"roundTrip\"]/a")).click();
    }
    public static void selectRJourney(WebDriver driver, WebElement element1, String returndate) {
        JavascriptExecutor je=(JavascriptExecutor)driver;
        je.executeScript("arguments[0].setAttribute('value','"+returndate+"');", element1);
        // TODO Auto-generated method stub

    }
    public static void selectJourney(WebDriver driver,WebElement element,String journeydate) {
        JavascriptExecutor js= (JavascriptExecutor)driver;
        js.executeScript("arguments[0].setAttribute('value','"+journeydate+"');",element);
    }

Would appreciate any insights or assistance in identifying what may have gone wrong or what steps I could potentially be overlooking?

Answer №1

Kindly utilize the following code snippet to set the calendar value by using

document.getElementById('datepicker1').value = "Your_Date"
.

String journeydate="04-10-2019";
selectJourneyDate(driver,journeydate);

Thread.sleep(3000);
String returndate="06-10-2019";
selectReturnJourneyDate(driver,returndate);

Code Modification:

public static void selectReturnJourneyDate(WebDriver driver, String returndate) {
    JavascriptExecutor je=(JavascriptExecutor)driver;
    je.executeScript("document.getElementById('datepicker2').value = '"+returndate+"';");

}
public static void selectJourneyDate(WebDriver driver,String journeydate) {
    JavascriptExecutor je=(JavascriptExecutor)driver;
    je.executeScript("document.getElementById('datepicker1').value = '"+journeydate+"';");

}

Recommendations:

  • Consider using id instead of xpath.

  • Avoid using JavascriptExecutor for real testing purposes.

  • Merge selectReturnJourneyDate and selectJourneyDate into a single method as they share similar code logic.

********************** EDITED *************************

String journeydate="04-10-2019";
pickDateFromCalendar(driver,"datepicker1",journeydate);

Thread.sleep(3000);
String returndate="06-10-2019";
pickDateFromCalendar(driver,"datepicker2",returndate);

You can create a generic method pickDateFromCalendar and pass the date picker id as an argument:

public static void pickDateFromCalendar(WebDriver driver, String datePickerId, String selectedDate) {
    JavascriptExecutor je=(JavascriptExecutor)driver;
    je.executeScript("document.getElementById('"+datePickerId+"').value = '"+selectedDate+"';");

}

***** HACK AS PER YOUR LEAD REQUIREMENT ******

driver.findElement(By.id("datepicker1")).click();
int currentSelectedDate = Integer.parseInt(driver.findElement(By.cssSelector(".ui-state-highlight")).getText());
driver.findElement(By.cssSelector(".ui-state-highlight")).click();
driver.findElement(By.id("datepicker2")).click();
if(currentSelectedDate>=30)
    driver.findElement(By.xpath("//a[@class='ui-state-default'][contains(text(),'1')]")).click();
else
    driver.findElement(By.xpath("//a[@class='ui-state-default'][contains(text(),'"+(currentSelectedDate+1)+"')]")).click();

Answer №2

Give this approach a try. I utilized Selenide, which takes care of the webdriver management automatically.

You have the flexibility to customize the date selection according to your requirements.

BusSearchTest.java

    package com.abhibus;

    import com.codeborne.selenide.Configuration;
    import com.codeborne.selenide.SelenideElement;
    import org.testng.annotations.BeforeMethod;
    import org.testng.annotations.BeforeTest;
    import org.testng.annotations.DataProvider;
    import org.testng.annotations.Test;

    import static com.codeborne.selenide.Condition.appear;
    import static com.codeborne.selenide.Condition.text;
    import static com.codeborne.selenide.Selenide.$;
    import static com.codeborne.selenide.Selenide.open;


    public class BusSearchTest {

        @DataProvider
        public static Object[][] itineraries() {
            return new String[][]{
                    {"Tenal", "Tenali", "Hyderaba", "Hyderabad", "Tenali → Hyderabad"}
            };
        }

        @BeforeTest
        public void setup() {
            Configuration.timeout = 10 * 1000;
        }

        @BeforeMethod
        public void beforeMethod() {
            open("https://www.abhibus.com/");
        }

        @Test(description = "Search Buses", dataProvider = "itineraries")
        public void busSearch(String from, String fromExpected, String to, String toExpected, String expected) {
            //to select leaving from
            $("#source").setValue(from);
            $("#ui-id-1 li.ui-menu-item")
                    .shouldHave(text(fromExpected))
                    .shouldBe(appear)
                    .click();
            //to select destination
            $("#destination").setValue(to);
            $("#ui-id-2 li.ui-menu-item")
                    .shouldHave(text(toExpected))
                    .shouldBe(appear)
                    .click();

            // from date: 04-October-2019
            $("#datepicker1").click();
            SelenideElement datePicker1 = $(".ui-datepicker-group-first");
            while (!datePicker1.find("span.ui-datepicker-month").text().trim().equals("October")) {
                $(".ui-datepicker-group-last").find("span").shouldHave(text("Next")).click();
            }
            datePicker1.findAll("tr td a").filterBy(text("4")).first().click();

            // to date: 06-October-2019
            $("#datepicker2").click();
            SelenideElement datePicker2 = $(".ui-datepicker-group-first");
            while (!datePicker2.find("span.ui-datepicker-month").text().trim().equals("October")) {
                $(".ui-datepicker-group-last").find("span").shouldHave(text("Next")).click();
            }
            datePicker2.findAll("tr td a").filterBy(text("6")).first().click();

            // click search
            $("a[title='Search Buses']").click();

            // assert search page
            $("#SubHead1way h1").shouldHave(text(expected));
        }
    }

pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>

        <groupId>tech.webisto</groupId>
        <artifactId>abhibus-tests</artifactId>
        <version>1.0-SNAPSHOT</version>
        <properties>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
        </properties>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.2</version>
                    <configuration>
                        <source>${maven.compiler.source}</source>
                        <target>${maven.compiler.target}</target>
                        <suiteXmlFiles>
                            <suiteXmlFile>test.xml</suiteXmlFile>
                        </suiteXmlFiles>
                    </configuration>
                </plugin>
            </plugins>
        </build>
        <dependencies>
            <dependency>
                <groupId>org.testng</groupId>
                <artifactId>testng</artifactId>
                <version>7.0.0</version>
            </dependency>
            <dependency>
                <groupId>com.codeborne</groupId>
                <artifactId>selenide</artifactId>
                <version>5.2.8</version>
            </dependency>
        </dependencies>
    </project>

The repository link for the code can be found here: https://github.com/WebistoTech/AbhiBusTests.git

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I divide a string using a particular character encoding error that is being received in Python?

I am currently using Selenium WebDriver to extract all text content from a Facebook profile, essentially performing data mining. I am encountering an issue when trying to parse by a specific character. Even though I encode it beforehand, I am still facing ...

Load and execute a dynamically created script in JavaScript at the same time

I am exploring the option to load and evaluate a script from a third-party synchronously. Here is an example that currently works well: <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Discovering the scroll position in Reactjs

Utilizing reactjs, I am aiming to manage scroll behavior through the use of a `click` event. To start, I populated a list of posts using `componentDidMount`. Next, upon clicking on each post in the list using the `click event`, it will reveal the post de ...

Utilizing dropbox.js in combination with OAuth 1: A step-by-step guide

I'm in the process of revamping a website that already exists, and although I have the code from the previous version, I'm encountering challenges replicating certain functionalities in the new iteration. Here's the situation: The user is ...

Discovering instructions on locating Material UI component documentation

I'm having trouble locating proper documentation for MUI components. Whenever I attempt to replicate an example from the site, I struggle to customize it to fit my requirements. There are numerous props used in these examples that I can't seem to ...

"An error occurred with the Google chart due to 'null' not being recognized as an object, specifically in relation to the select menu and onchange event

Currently, I have implemented the following Script: <header> <script type="text/javascript" src="http://www.google.com/jsapi"></script> </header> <body> <script type="text/javascript"> google.load("visualization", "1 ...

Performing an asynchronous POST request in JavaScript

Hey there, I successfully managed to implement a post request using ajax for my submit functionality. However, I am now looking to make this asynchronous to account for any delays in processing by my php file. Unfortunately, I am struggling to figure out h ...

What are some creative ways to utilize postMessage instead of relying on nextTick or setTimeout with a zero millisecond delay?

I just came across a theory that postMessage in Google Chrome is similar to nextTick. This idea somewhat confused me because I was under the impression that postMessage was primarily used for communication between web workers. Experimenting with expressio ...

Exploring the Method of Accessing data-* Attributes in Vue.js

I have a button that, when clicked, triggers a modal to open. The content displayed in the modal is determined by the data attributes passed to the button. Here is my button: <button class="btn btn-info" data-toggle="modal" data-t ...

Ways in which the user can modify the city name within this inquiry

I am just beginning to learn JavaScript and I am struggling to figure out how to allow the user to change the city name in this request. Currently, it works when I manually input the city name in the code (e.g., askWeather.open("GET", "url.../london")), bu ...

A guide to updating property values in an array of objects in JavaScript while ensuring they remain in consecutive order

I am dealing with an array of objects called list. The parameters rid and rorder are provided for processing. -> 1. Whenever the value of rid matches the id in the list, the itemorder is updated with the value of rorder. -> 2. In the updated list p ...

The Lerna command for adding packages fails with an error message stating that the packages are not related

Currently, I am utilizing lerna to manage a multirepo containing interrelated packages. This issue only arose after installing a new operating system. Whenever I attempt to utilize lerna add to add a dependency from one package to another, an error occurs ...

Can the top header stay fixed to the top of the screen even when scrolling down?

Code snippet: http://jsfiddle.net/R3G2K/1/ In my project, there are multiple divs with content and each div has a header. My goal is to make the last header that goes out of viewport "sticky" or fixed at the top. I have explored various solutions for thi ...

What steps should I take to ensure that the array yields the correct output?

Why is my code not creating an array of [0, 1, 2] when I pass the number 3 as a parameter? const array = [0]; const increment = (num) => { if (num > 0) { increment(num - 1); array.push(num); } return; }; console.log(array); incremen ...

Having difficulty in executing the node app.js script

I am currently learning node.js and encountering an issue when trying to run the app.js file using the command node app.js. The terminal shows no output, neither errors nor any other information. Here is the sequence of steps I have followed: $ brew insta ...

How to use Javascript to fetch HTML content from an external website

Is it possible to access and retrieve scores from for a specific week using AJAX or JSON technology? Each game on the website seems to have a unique class which could make retrieving score information easier. Any guidance or assistance would be greatly ap ...

Can variables in JavaScript clash with input names in HTML?

I have the following code in an HTML file: <input type="..." name="myInput1" /> Then, in a JS file associated with this HTML file, I declare a variable to store the value of that input after it loses focus: var myInput1; Should I be concerned abo ...

streamlining the deletion of Yahoo emails

Currently, I am utilizing Selenium IDE within Firefox to remove unread emails from Yahoo mail. With approximately 30,000 unread emails in our inbox, it seems that Yahoo only deletes less than 100 at a time. I have recorded the necessary steps for this pro ...

Load Bootstrap 4 Modal with Ajax

I recently upgraded from Bootstrap 3 to Bootstrap 4.1 Within my applications, I utilize ajax loaded modals. In the layout, I have: <div class="modal fade" id="myModalToFillInfo" tabindex="-1" role="dialog" aria-labelledby="myModalToFillInfoLabel" ari ...

Issue with reactivity not functioning as expected within VueJS loop without clear explanation

Struggling with implementing reactivity in vue.js within a loop? The loop renders fine, but firing an event updates the content without visibly rendering the data on the page. The latest version of vue.js is being used with bootstrap and jquery. Despite a ...