This question already has answers here:
Select from a DatePicker in Python
(3 answers)
Closed 3 years ago.
Am trying to automate a date picker,on clicking the ok button date should be displayed in date box.I have two date pickers like for a start date and the other is for the end date.One date picker is registering the date but the other date picker is not registering the date,neither i get any error.Please help,it's urgent.Here is my code..
package DatePicker;
import java.util.List;
import java.util.concurrent.TimeUnit;
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.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class DatePickerTest
{
WebDriver driver;
Actions builder;
#BeforeMethod
public void setup()
{
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
driver.get("http://localhost/able/public/index.php/get_inputs");
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
System.out.println("Hello client");
}
#Test
public void TestDate() throws Exception
{
WebDriverWait wait=new WebDriverWait(driver,3);
Boolean invisible=wait.until(ExpectedConditions.invisibilityOfElementLocated(By.className("preloader")));
if(invisible)
{
driver.findElement(By.xpath("//*[#id=\"add-edit-form\"]/div[3]/div[1]")).click();
}
Thread.sleep(2000);
WebElement web11=driver.findElement(By.className("dtp-btn-ok"));
web11.click();
Thread.sleep(2000);
driver.findElement(By.id("Contract_e_date")).click();
Thread.sleep(1000);
builder= new Actions(driver);
//Thread.sleep(1000);
WebElement web2=driver.findElement(By.className("dtp-btn-ok"));
//Thread.sleep(1000);
builder.moveToElement(web2).click(web2);
//web2.click();
Thread.sleep(1000);
builder.perform();
}
}
Look here:
WebElement web11=driver.findElement(By.className("dtp-btn-ok"));
WebElement web2=driver.findElement(By.className("dtp-btn-ok"));
If your 2 datepickers have the same CSS class - Selenium will always find the first one and perform operations on the first item found.
Quick and dirty solution would be switching to WebDriver.findElements() function which returns the List of WebElements like:
List<WebElement> datepickers = driver.findElements(By.className("dtp-btn-ok"));
WebElement web11 = datepickers.get(0);
WebElement web2 = datepickers.get(1);
A better solution would be choosing the right Locator Strategy so your locator would uniquely match this or that datepicker (look into their parents, associated text, etc.)
Also be aware that using Thread.sleep is a some form of a performance anti-pattern, consider using WebDriverWait instead, check out How to use Selenium to test web applications using AJAX technology for more details if needed.
Related
I have a button on my Webpage which I want to click once the required piece of information is entered. I am currently using By to establish all the elements of the page but want to use WebElements for this button and then use Actions to click it later.
How should I do that in my Page Object class.
I tried with below approach :
WebElement addressinput = driver.findElement(By.xpath("//input[#id='pac-input']"));
By addressinput = By.xpath("//input[#id='pac-input']");//this works fine
But on running the Test class as TestNG it shows null pointer exception on WebElement line. Tried to do it with By as well but the button just won't recieve the click. It works pefectly fine with WebElements and action which I have tried before without using POM below is the reference code for that :
WebElement button = driver.findElement(By.xpath("//button[#id='btn_gtservice']"));
Actions action = new Actions(driver);
action.moveToElement((WebElement) CheckAvailability).click().perform();
driver.switchTo().defaultContent();
You've got
action.moveToElement((WebElement)CheckAvailability)
That should be
action.moveToElement((button)CheckAvailability)
As it is, you'll be getting a null pointer as you have no variable named WebElement defined
When using PageFactory in PageObjectModel if you expect the element to be loaded after some information is entered, through some JavaScript and it might not be immediately present on the page already you can use the Actions once the element is returned through WebDriverWait support with a normal locator factory as follows:
Code Block:
package com.pol.zoho.PageObjects;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.interactions.Actions;
public class ZohoLoginPage {
WebDriver driver;
public ZohoLoginPage(WebDriver driver)
{
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//button[#id='btn_gtservice']")
public WebElement myButton;
public void doLogin(String username,String userpassword)
{
WebElement button = new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(ZohoLoginPage.getWebElement()));
new Actions(driver).moveToElement(button).click().perform();
}
public WebElement getWebElement()
{
return myButton;
}
}
You can find a detailed discussion in How to use explicit waits with PageFactory fields and the PageObject pattern
This question already has an answer here:
Gmail login using selenium webdriver in java
(1 answer)
Closed 4 years ago.
package Login;
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 Login
{
public static void main(String[] args) throws Exception
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Teknomines-5\\Downloads\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com/intl/en-GB/gmail/about/");
//Thread.sleep(5000);
driver.findElement(By.xpath("/html/body/nav/div/a[2]")).click();
driver.findElement(By.xpath("//*[#id=\"identifierId\"]")).sendKeys("Pratik.modh24#gmail.com");
driver.findElement(By.xpath("//*[#id=\"identifierNext\"]")).click();
//Below Code password not print on PAssword textbox
//driver.findElement(By.xpath("/html/body/div[1]/div[1]/div[2]/div[2]/div/div/div[2]/div/div[1]/div/form/content/section/div/content/div[1]/div/div[1]")).sendKeys("123");
//driver.findElement(By.className("whsOnd zHQkBf")).sendKeys("123");
//driver.findElement(By.id("Passwd")).sendKeys("test123");
//driver.findElement(By.name("password")).sendKeys("123");
//driver.findElement(By.xpath(".//*[#id='Passwd']")).sendKeys("123456789");
//driver.findElement(By.cssSelector("#password > div:nth-child(1)")).sendKeys("123");
//driver.findElement(By.xpath("//INPUT[#name='password']")).sendKeys("******");
//driver.findElement(By.xpath("//INPUT[#type='password']/self::INPUT")).sendKeys("***");
//driver.findElement(By.xpath("(//DIV[#class='aCsJod oJeWuf'])[1]")).sendKeys("123456");
WebElement password = driver.findElement(By.xpath("//input[#name='password']"));
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(password));
password.sendKeys("your_password");
}
}
This XPATH should select gmail "password input": //input[#name='password']
But you don't have to use XPATH, you can target the input field by lot of other ways. For instance I am using this (in Python):
WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.NAME, 'password'))).send_keys('my_password')
EDIT:
Also try changing the order of your commands to:
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[#name='password']")));
password.sendKeys("your_password");
because you are creating the password variable WebElement password = driver.findElement(By.xpath("//input[#name='password']")); before you wait for it to appear on DOM: wait.until(ExpectedConditions.elementToBeClickable(password));
this is working one
driver.manage().window().maximize();
driver.get("https://www.google.com/intl/en-GB/gmail/about/");
driver.findElement(By.xpath("/html/body/nav/div/a[2]")).click();
driver.findElement(By.xpath("//*[#id=\"identifierId\"]")).sendKeys("Pratik.modh24#gmail.com");
driver.findElement(By.xpath("//*[#id=\"identifierNext\"]/content/span")).click();
WebElement password = driver.findElement(By.name("password"));
password.sendKeys("your_password");
Pardon me for any silly mistakes, I am still an amateur
Also I am able to run the code just the drop down selection part is not working
Here is the code
package com.thinksys.dd;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class Autodd
{
public static void main(String[] args)
{
System.setProperty("webdriver.gecko.driver","C:\\Users\\thinksysuser\\Downloads\\geckodriver-v0.18.0-win64\\geckodriver.exe");
WebDriver driver= new FirefoxDriver();
driver.get("http://newtours.demoaut.com/mercuryregister.php?%20osCsid=e6b6a3a86207b80bb2d346a613c378da");
WebElement e = driver.findElement(By.name("country"));
Select index = new Select(e);
index.selectByVisibleText("PORTUGAL");
}
}
Replace your code with below code.It should work.
index.selectByVisibleText("PORTUGAL ");
The actual issue here is not with the select class or with its methods. We are missing implicit wait here. Just add implicit wait after initiating the driver and the code works fine then.
System.setProperty("webdriver.gecko.driver", "/home/santhoshkumar/Softwares/Selenium/drivers/geckodriver");
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("http://newtours.demoaut.com/mercuryregister.php?%20osCsid=e6b6a3a86207b80bb2d346a613c378da");
WebElement e = driver.findElement(By.name("country"));
Select index = new Select(e);
index.selectByVisibleText("PORTUGAL");
Hope this helps. Thanks.
The problem was there due to the fact that my Firefox browser was not updated to the most recent version and since I have done that it is running just fine.
Try this code using xpath locator.
Note:- Provide few seconds of wait before execute below code and Instead of using absolute xpath, use relative xpath.
new Select(driver.findElement(By.xpath("//select[#name='country']"))).selectByVisibleText("PORTUGAL");
OR
new Select(driver.findElement(By.xpath("//select[#name='country']"))).selectByValue("167");
package p111;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Yahoo_c
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
WebDriver wi= new FirefoxDriver();
wi.get("https://in.yahoo.com/?p=us");
WebElement q=wi.findElement(By.xpath("//*[starts-with(.,'UHSearch')]")); q.sendKeys("pizza");
}
}
//Actual xpath is :
input id="UHSearchBox".
I tried with //*[starts-with(#id,'UHSearch')] but it does not work.
Any ideas?
You have make 2 mistake.
You have write wrong xpath
If you are able to find element with help of starts-with , It will give you more than one elements (Means list of elements).
Use following element finder :
xpath : //input[#id='UHSearchBox']
id : id= UHSearchBox
css = input[id='UHSearchBox'] or #UHSearchBox
I am trying to automate google search,normal sendkeys is working ,but when I try to send using keys.F5 or ascii code ,refresh wont work
also when try to do location reload it gives error as " The method execute_script(String) is undefined for the type WebDriver
"
Tried instead of F5 ,F1 key also but no avail
` package com.at.sample;
import org.openqa.selenium.Keys;
import java.lang.Thread;
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.interactions.Actions;
// import org.openqa.selenium.Alert;
import java.util.List;
public class Refreshgoogle {
public static void main(String[] args) throws InterruptedException {
WebDriver driver;
System.setProperty("webdriver.chrome.driver","c://chromedriver.exe");
driver= new ChromeDriver();
//Launch the Application Under Test (AUT)
driver.get("http://google.com");
Actions action = new Actions(driver);
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("test data");
//sends normal keybaord strokes
// approch 1 driver.findElement(By.xpath("//html")).sendKeys(Keys.F5);
// approch 2.1 WebElement element1 = driver.findElement(By.xpath("//*[#id=\"tsf\"]/div[2]/div[1]/div[2]/div[2]"));
//approch 2.2 element1.sendKeys(Keys.F1);
// approch 3 driver.findElement(By.xpath("//*[#id=\"gsr\"]")).sendKeys(Keys.F5);
// driver.execute_script("location.reload(true);");
System.out.println(driver.getTitle());
// working driver.navigate().to(driver.getCurrentUrl());
}
}
`
There are 4 approaches
First 3 wont refresh pagea
when used 4th it shows error as The method execute_script(String) is undefined for the type WebDriver
You can refresh in below ways:
1.Using get method and recursive way
driver.get("https://URL.com");
driver.get(driver.getCurrentURL());
Using Navigate method and Recursively calling your URL
driver.get("https://URL.com");
driver.navigate.to(driver.getCurrentURL());
Using one valid webelement and send keys
driver.get("https://URL.com");
driver. findElement(By.id("username")).sendKeys(Keys.F5);
Hope this help.
Please refer below solution
driver.navigate.refresh();
If you want to refresh your page using keys then you can also use Robot class.
Robot robot = new Robot(); // Robot class throws AWT Exception
Thread.sleep(2000); // Thread.sleep throws InterruptedException
robot.keyPress(KeyEvent.VK_CONTROL); // press Control key down key of
robot.keyPress(KeyEvent.VK_F5);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_F5);
Thread.sleep(2000);
This is selenium related issue more details available here: https://github.com/webdriverio/webdriverio/issues/1344
WebElement(I) sendKeys() will not accept Keys (keyboard keys). This can be handled using Actions class only.
Additionally, if you need to refresh the page, use WebDriver() refresh() or get current URL using getCurrentUrl() of same interface and navigate() using same url as parameter.
Update:
Here is the detailed explanation on each approach:
1) As per 'https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/WebElement.html#sendKeys-java.lang.CharSequence...-', sendKeys() in WebElement(I) accepts only char sequence (i.e. string.).
// approch 1 driver.findElement(By.xpath("//html")) returns a WebElement and this element sendKeys will accept only char sequence. Hence, your approach r=to refresh using Keys.F5 won't work here.
2) // approch 2.1 WebElement element1 = driver.findElement(By.xpath("//*[#id=\"tsf\"]/div[2]/div[1]/div[2]/div[2]"));
//approch 2.2 element1.sendKeys(Keys.F1);
Same explanation as approach 1.
3) // approch 3 driver.findElement(By.xpath("//*[#id=\"gsr\"]")).sendKeys(Keys.F5);
Did the same kind of operation as approach 1 and is explained there.
4) If we need to use javascriptexecutor, first we need to create javascriptexecutor object like below and should call execute_script() using reference variable of that object:
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(Script,Arguments);
If you are not created this object, you will get 'execute_script(String) is undefined for the type WebDriver', which is expected.
Hence, the 4 approaches what you tried will not refresh the page.
Instead, you can use below options:
1) Actions class sendKeys(): which will accept keyboard keys.
2) using driver.navigate().refresh();
3) Using javascriptexecutor after creating an object for the same (as explained in approach 4)
Try with this code:
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class TestRefresh {
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.google.com");
`// case 1:`
`driver.navigate().to(driver.getCurrentUrl());`
`// case 2:`
`((JavascriptExecutor)driver).executeScript("document.location.reload()");`
`// case 3:`
`driver.navigate().refresh();`
}
}