I am trying to test a trip planner website using selenium webdriver.
Say for e.g. I am testing cleartrip.com.
How to select a city from the lookup field using selenium?
For instance, I have to select the source city.
If I type DE, it gives me options like "Delhi, "Dehradun" based on what I have typed and out of these options, I have to select say Delhi.
How to achieve it using Selenium? Kindly suggest.
I am new to selenium and any help would be appreciated.
This code works for me
WebDriver driver = new FirefoxDriver();
driver.get("http://www.cleartrip.com/");
WebElement From = driver.findElement(By.id("FromTag"));
From.sendKeys("Del");
WebElement autoComplete = driver.findElement(By.id("ui-id-1"));
try{
(new WebDriverWait(driver, 5/*sec*/)).
until(ExpectedConditions.presenceOfElementLocated((By.cssSelector("li.list")))); }
catch(org.openqa.selenium.TimeoutException e){
System.out.println(e.getMessage());
}
List<WebElement> autoCompleteList = autoComplete.findElements(By.className("list"));
if(autoCompleteList.size()==0) {
System.out.println("autoComplete list NOT found");
}
else {
System.out.println("autoComplete list Found with elements: "+autoCompleteList.size());
}
for (WebElement ac: autoCompleteList){
if(ac.getText().contains("Delhi")){
ac.click();
break;
}
}
driver.close();
Please note this is just example, please improve the code adding verifications that objects not a null, remove the hardcoded strings, etc.
You can simply achieve it by putting up some wait and then clicking the desired city, like:
public CurrentPage selectFrom(String cityCode, String cityName){
driver.findElement(By.id("FromTag")).sendKeys(cityCode);;
new WebDriverWait(driver, 5).until(
ExpectedConditions.elementToBeClickable(
By.xpath(".//*[#id='ui-id-1']//a[contains(.,'" + cityName + "')]")))
.click();
return this;
}
Related
I am working on automating the following hotel booking site. I need to select the auto popup hotel name once I type the hotel in the first search box...I don't know how to do this.
I have navigated through the link and clicked Demo, then clicked the first link that appeared on the page.
I tried to click on the first search box and I need to enter a hotel from the auto popup list...I don't know how to do this because this has no PAC-item...
https://www.phptravels.net/home
public class Question1 {
WebDriver Driver = null;
WebDriverWait wait = null;
String url = "https://phptravels.com/demo/";
#BeforeTest
public void beforeTest() {
System.setProperty("webdriver.chrome.driver","src\\test\\resources\\drivers\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("excludeSwitches",Arrays.asList("disable-popup-blocking"));
options.addArguments("--disable-popup-blocking");
Driver = new ChromeDriver(options);
Driver.manage().window().maximize();
Driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
wait = new WebDriverWait(Driver, 25);
String winHandle = Driver.getWindowHandle();
//Driver.switchTo().window(winHandle);
//new WebDriverWait(Driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe[title='webpush-onsite']")));
//new WebDriverWait(Driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("button#deny.button.close"))).click();
}
#Test
public void f() {
Driver.get(url);
System.out.println("*****In the main page*****");
String xpathDemo = "//*[#id=\"mega-nav-navigation\"]/div/ul[1]/li[2]/a";
Driver.findElement(By.xpath(xpathDemo)).click();
String Title = "PHPTRAVELS | Travel Technology Partner";
/*try {
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath("//*[#id=\"PopupSignupForm_0\"]/div[2]/div[1]")));
Driver.findElement(By.xpath("//*[#id=\"PopupSignupForm_0\"]/div[2]/div[1]")).click();
} catch(Exception e) {
System.out.println("No popup..."+ e.getMessage());
}
*/
String username = Driver.findElement(By.xpath("//*[#id=\"Main\"]/section[2]/div/div/div[2]/div/div/div[2]/div[2]/div/div[3]/div[2]/div")).getAttribute("innerText");
username = username.substring(6) ;
String password = username.substring(30);
System.out.println("Username text :"+username + "\npassword is:"+password);
Driver.findElement(By.xpath("//*[#id=\"Main\"]/section[2]/div/div/div[2]/div/div/div[2]/div[2]/div/div[1]/div/a")).click();
utils.HelperFunctions2.switchToWindow(Driver, Title);
Driver.findElement(By.xpath("//*[#id=\"s2id_autogen16\"]")).click();
Driver.findElement(By.xpath("/html/body/div[7]/ul")).click();
}
#AfterTest
public void afterTest() {
Driver.quit();
}
}
Below xpath is result of 1st hotel, changing the index it will intreact with rest of the elements.
After filing text to the hotel text box.
give Thread.sleep(2000);
use below xpath. I hope it will work
(.//ul[#class='select2-results']/following::div[#class='select2-result-label'])[2]
I have already built bots, auto image pickers and more and I have never used the By.xpath method. Classname is much easier to use!
public void f(){
Driver.get(url);
String getInputFocusId = "select2-input";
Driver.findElement(By.className(getInputFocusId).click();
//now focused!
String text = Driver.findElement(By.className("select2-match").getText();
//text is the first default search match of the list.
}
There is also a more complicated way.
In Selenium you can sendKeys to an Element.
If the input element is focused the first match is also focused.
By clicking on Enter the focused match will be searched and displayed in the input element.
Finally you have to read the data from the input Element!
public void f(){
Driver.get(url);
String getInputFocusId = "select2-input";
WebElement element = Driver.findElement(By.className(getInputFocusId);
element.click();
//element.sendKeys(Key.DOWN);
element.sendKeys(Key.ENTER);
String text = element.getText();
//this is the text of the first search match
//if you want to get the second or third just repeat sending the DOWN key.
}
IMPORTANT: Make sure to run each line delayed (200ms is a good time). This helps you finding errors... For example in the Instagram Auth Process I delayed a lot of lines, and it finally worked!
I hope my answer helps you!!!
I am having problem with locating WebElement using different locators. In the below html tag I tried locating the "write a review" WebElement with different locators like linkText,xpath,classname but still getting NoSuchElementException
-->url https://www.tripadvisor.in/-->search for Club Mahindra-->click on Club Mahindra-->click on write a review.
<a href="/UserReview-g641714-d1156207-Club_Mahindra_Madikeri_Coorg-
Madikeri_Kodagu_Coorg_Karnataka.html" target="_blank" class="ui_button
primary">Write a review</a>
Locators used
By.xpath("//*[#id="component_12"]/div/div[2]/div/div[2]/div/div[1]/a")
By.xpath("//a[#href='/UserReview-g641714-d1156207-
Club_Mahindra_Madikeri_Coorg-Madikeri_Kodagu_Coorg_Karnataka.html']")
By.className("ui_button primary")
By.linkText("Write a review")
I am really confused. What am I doing wrong?
I have tired to analyse and implement the same. Below are my findings:
-> Application waiting time is more as there are lots of dynamic loads applicable for the page.
-> Proper waits needs to be implemented
-> Check whether all the pages are getting opened in the same tab or clicking on each link is redirecting to new tabs, if so then we have to switch to that particular window.
-> Below code works like a pro for me.
driver.get("https://www.tripadvisor.in/");
WebDriverWait wait = new WebDriverWait(driver, 120);
WebElement ele1 =
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[text()='Where to?']")));
ele1.click();
WebElement ele2= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[#placeholder='Where to?']")));
ele2.sendKeys("club mahindra, india");
WebElement ele3= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Search for ')]")));
ele3.click();
WebElement ele4= wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Club Mahindra Madikeri, Coorg')]")));
ele4.click(); //this click leads to a new tab
Set<String> winHandles = driver.getWindowHandles();
for(String str : winHandles) {
driver.switchTo().window(str);
}
System.out.println(driver.getTitle());
WebElement ele;
int i=1;
while(true) {
try {
ele = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//*[text()='Write a review']")));
break;
}catch(Exception e) {
System.out.print(i++);
}
}
System.out.println();
Actions action = new Actions(driver);
action.moveToElement(ele);
ele.click();
System.out.println("Clicked on the 'Write a review button'");
you can try
//a[contains(text(),'Write a review')]
To get the element I have used a nested loop.I am able to click on dropdwn.PFB the code:
List<WebElement> webElements1 = driver.findElements(By.className("selectboxit"));
for(WebElement webElement1 : webElements1) {
if( webElement1.getAttribute("name").equals("TransactionHistoryFG.OUTFORMAT"))
{
WebElement web1 = webElement1.findElement(By.className("selectboxit-text"));
web1.click();
}
}
When i am trying to use Select on webelement i am getting error :
org.openqa.selenium.support.ui.UnexpectedTagNameException: Element
should have been "select" but was "span"
How can i select dropdown i span element?
Possible solution for selecting dropdown using selenium webdriver is:
Select select = new Select(driver.findElement(By.xpath("//path_to_drop_down")));
select.deselectAll();
select.selectByVisibleText("Value1");
Instead of the approach you mentioned above, let me know if this helps :)
List<WebElement> webElements1 = driver.findElements(By.cssSelect(".selectboxit"));
for(WebElement webElement1 : webElements1) {
if( webElement1.getAttribute("name").equals("TransactionHistoryFG.OUTFORMAT"))
{
WebElement web1 = webElement1.findElement(By.className("selectboxit-text"));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click();", web1);
}
}
Well, it is not the best way to do it, but in some cases it can be used:
it will open your combobox
driver.findElements(By.cssSelect(".selectboxit")).click()
now, you just need to write the specified value
driver.findElements(By.cssSelect(".selectboxit")).sendKeys("<value>");
OR
driver.findElements(By.cssSelect(".selectboxit")).sendKeys(Keys.ARROW_DOWN).
Use "ARROW_DOWN" as wanted to select your specified value.
Not able to Select the month for Date of Birth.
Code I am using is:
driver.findElement(By.xpath(".//*[#id = 'BirthMonth']/div")).click();
Thread.sleep(3000);
WebElement months = driver.findElement(By.xpath(".//[#id='BirthMonth']/div[2]/div[#id=':1']"));
Thread.sleep(2000);
months.click();
I also tried with by using DropDownList case. But Not able to set any Month.
Please Say me the Solution.
You can use keyboard event replace mouse.
WebElement birthMonth = driver.findElement(By.id("BirthMonth"));
birthMonth.click();
Actions action = new Actions(driver);
action.sendKeys(Keys.DOWN).sendKeys(Keys.ENTER).perform();
We can use sendKeys directly:
driver.findElement(By.xpath(".//*[#id='BirthMonth']/div[1]")).sendKeys("July");
You can wrap this up in a function
public void selectBirthMonth(int monthIndex)
{
driver.findElement(By.cssSelector("#BirthMonth > div")).click();
driver.findElements(By.cssSelector("#BirthMonth > div.goog-menu > div.goog-menuitem")).get(monthIndex - 1).click();
}
and then call it like
selectBirthMonth(9); // 1 = January
WebElement month = wd.findElement(By.xpath("//[#id=\"BirthMonth\"]/div[1]"));
month.click();
Thread.sleep(3000);
//wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//fetch months from the dropdown and store it in a list
List<WebElement> month_dropdown = wd.findElements(By.xpath("//[#id=\"BirthMonth\"]/div[2]/div/div"));
//iterate the list and get the expected month
for (WebElement month_ele:month_dropdown){
String expected_month = month_ele.getAttribute("innerHTML");
// Break the loop if match found
if(expected_month.equalsIgnoreCase("August")){
month_ele.click();
break;
}
}
It is not drop down value , you have to click on drop down arrows and then click on any value which you have to pass from script.
Code is below:
System.setProperty("webdriver.chrome.driver", "E:/software and tools/chromedriver_win32/chromedriver.exe");
WebDriver driver= new ChromeDriver();
//FirefoxDriver driver= new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://accounts.google.com/SignUp");
Thread.sleep(5000);
driver.findElement(By.xpath(".//*[#id='BirthMonth']/div[1]/div[2]")).click();
driver.findElement(By.xpath(".//*[#id=':7']/div")).click();
it is workable code for Birthmonth
Please find below link for same type of Question
Not able to select the value from drop down list by using Select method in Selenium
I have tried with below coding to obtain the text from table.It works fine.But ,i want pick the data from first column alone.How can i grab the text from first column. .
WebElement tableContents = pubDriver.findElements(By.id("view_table"));
List<WebElement> rows=tableContents.findElements(By.tagName("tr"));
for(int rnum=0;rnum<rows.size();rnum++)
{
List<WebElement> columns=rows.get(rnum).findElements(By.tagName("td"));
for(int cnum=0;cnum<columns.size();cnum++)
{
System.out.println(columns.get(cnum).getText());
}
}
I have tried with below coding ,i didn't get the text from first column
columns.get(0).getText();
you can do like this....
// Create a new instance of the html unit driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://localhost:8081/TestXmlDisplay/tabletest.html");
WebElement tableContents = driver.findElement(By.tagName("table"));
List<WebElement> rows=tableContents.findElements(By.tagName("tr"));
for(int rnum=0;rnum<rows.size();rnum++)
{
List<WebElement> columns=rows.get(rnum).findElements(By.tagName("td"));
System.out.println(columns.get(0).getText());
}
// driver.quit();