When I run the webdriver it runs too fast.
The webdriver is moving the next element before the first one appears.
Can I make webdriver slower?
Thanks!
If you are using java, you can do implicit waits on every page found here
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
but a better way of doing this is by using fluent waits, to wait for a element to appear on the page, like this
public WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
}
);
return foo;
};
and you can use it by
WebElement element = fluentWait(By.id("name"));
element.click();
This is a great answer to read over answer to waits with selenium
Related
I need to fill out the phone number field (with a placeholder = "(__) -") using Selenium WebDriver. The issue I'm facing is: the driver does it very quickly and the first number is missing in 40% of my tests. I mean the number is 965-234-43 and what the driver does is 652 - 34 - 43_.
My code is:
private void setBankPhone(String bankPhone) {
driver.findElement(bankPhoneField).click();
driver.findElement(bankPhoneField).clear();
driver.findElement(bankPhoneField).sendKeys(Keys.HOME + bankPhone);
checkBankPhone(bankPhone);
}
private void checkBankPhone(String bankPhone){
WebElement phonElement = driver.findElement(bankPhoneField);
if (!phonElement.getAttribute("value").equals(bankPhone)) {
setBankPhone(bankPhone);
}
}
With driver.findElement(bankPhoneField).sendKeys(bankPhone); it's impossible to fill out the field at all.
Though your code looks fine to me, I believe it's a latency/sync issue.
Can you try any of the below approaches before entering text to make sure readiness of the element?
1. Wait for JavaScript to load
WebDriverWait wait = new WebDriverWait(driver, timeOut);
JavascriptExecutor js_Executor = (JavascriptExecutor) getDriver();
ExpectedCondition<Boolean> jsLoad = driver -> js_Executor.executeScript("return document.readyState").toString().equals("complete");
ExpectedCondition<Boolean> jQueryLoad = driver -> js_Executor.executeScript("return jQuery.active").toString().equals("0");
// Wait for JavaScript and jQuery to be loaded.
wait.until(jsLoad);
wait.until(jQueryLoad);
2. Use wait conditions
WebDriverWait wait = new WebDriverWait(driver, timeOut);
wait.until(ExpectedConditions.elementToBeClickable(webElement));
Explicit wait is not working for Firefox (52.4.0 (64-bit))below is my code:
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://XXXX/XXXXX/XX/login");
driver.findElement(By.id("userId")).sendKeys("XXXXX");
driver.findElement(By.id("password")).sendKeys("XXXXX");
driver.findElement(By.id("submit")).click();
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//span[text()='Viewer']")));
driver.findElement(By.xpath("//span[text()='Viewer']")).click();
}
I have to use Explicit wait here in any case as elements doesn't get loaded in fixed time. I have searched lot in google but didn't find any code working for me.
As per your code attempt it seems you are waiting for the WebElement through WebDriverWait and then trying to invoke click() method. In your code you have used the clause presenceOfElementLocated with ExpectedConditions, which as per the documentation doesn't confirms if the WebElement is Displayed and Enabled as well.
A better solution will be to modify the clause for ExpectedConditions where instead of presenceOfElementLocated we have to use elementToBeClickable as follows:
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Viewer']")));
You are using presenceOfElementLocated. As per documentation:
An expectation for checking that an element is present on the DOM of a
page. This does not necessarily mean that the element is visible.
You have to be sure that you are waiting on the element the correct expected condition.
as per #DebanjanB , i just it is not an good idea to use presenceOfElementLocated instead it is always better to use elementToBeClickable so correct code should be:
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://XXXX/XXXXX/XX/login");
driver.findElement(By.id("userId")).sendKeys("XXXXX");
driver.findElement(By.id("password")).sendKeys("XXXXX");
driver.findElement(By.id("submit")).click();
WebDriverWait wait = new WebDriverWait(driver, 50);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[text()='Viewer']")));
driver.findElement(By.xpath("//span[text()='Viewer']")).click();
}
I'm new in Selenium webdriver and learning the Dynamics table as the moment im stuck at point. i want to click particular company name in dynamics table i have written sample scripts for it please let me whats wrong with it.
im using icicidirect website.
Selecting the Market link from main menu bar
Now at the bottom of the page their is one link "Daily Share Prices" link (its below the "Top Losers" section will get it by using ctrl+f)
At Daily Share Prices in first column (Security Name) i.e.ABB link element is their
and i want to click that element
public static void main(String[] args) throws Exception {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.icicidirect.com");
Thread.sleep(1000);
driver.findElement(By.xpath("//a[contains(text(),'Markets')]")).click();
Thread.sleep(3000);
driver.findElement(By.xpath("//a[contains(text(),'Daily Share Prices')]")).click();
Thread.sleep(3000);
TablePageObject tablePageObject = PageFactory.initElements(driver, TablePageObject.class);
tablePageObject.clickLink("ABB");
}
}
public class TablePageObject {
private WebDriver driver;
#
FindBy(css = "table tr")
private List < WebElement > allTableRows; // find all the rows of the table
public TablePageObject(WebDriver driver) {
this.driver = driver;
}
public void clickLink(String SecurityName) {
for (WebElement row: allTableRows) {
List < WebElement > links = row.findElements(By.linkText("ABB"));
// the first link by row is the company name, the second is link to be clicked
if (links.get(0).getText().contains(SecurityName)) {
links.get(0).click();
}
}
}
}
Several suggestions:
You may use the following link in order to receive the required table directly
driver.get("http://content.icicidirect.com/newsiteContent/Market/MarketStats.asp?stats=DailySharePrices");
You may wait for the table loading
Then you will found the element and click it (like in your code).
This is code that works for me
WebDriver driver = new FirefoxDriver();
try{
driver.get("http://content.icicidirect.com/newsiteContent/Market/MarketStats.asp?stats=DailySharePrices");
(new WebDriverWait(driver, 10/*sec*/)).until(ExpectedConditions.presenceOfElementLocated(By.linkText("ABB")));
List<WebElement> dailyList = driver.findElements(By.linkText("ABB"));
if (dailyList.size()!=0) {
dailyList.get(0).click();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally{
driver.close();
}
If you need find some element that not located on the first page you may extend this solution to click on the Next>> link and back to this loop improving it by removing hard coded "ABB" element.
I want to do the following, can someone help me what wrong i have done..
1) open the site mentioned in code
2) Enter the Text "WELcoME" (mixture of capital and small letters) using keydown and keyup events in webdriver.
public class KeysUpandDown {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://fleet.idrivesafely.com");
driver.manage().window().maximize();
driver.findElement(By.linkText("Student Login")).click();
WebElement loc=driver.findElement(By.className("input1"));
Actions a= new Actions(driver);
a.moveToElement(loc)
.keyDown(Keys.SHIFT)
.sendKeys("wel")
.keyUp(Keys.SHIFT)
.sendKeys("co")
.keyDown(Keys.SHIFT)
.sendKeys("me");
a.perform();
}
}
Your code requires 2 small changes.
Change 1:
WebElement loc=driver.findElement(By.className("input1"));
is pointing to three Web-elements on the page, Instead use below
WebElement loc=driver.findElement(By.xpath("//input[#class='input1' and #name='pin_no']"));
Change 2: Its a Text field, so Instead of
a.moveToElement(loc)
Use
a.click(loc)
So you code should be as below :
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://fleet.idrivesafely.com");
driver.manage().window().maximize();
driver.findElement(By.linkText("Student Login")).click();
WebElement loc=driver.findElement(By.xpath("//input[#class='input1' and #name='pin_no']"));
Actions a= new Actions(driver);
a.click(loc).keyDown(Keys.SHIFT).sendKeys("wel").keyUp(Keys.SHIFT).sendKeys("co").keyDown(Keys.SHIFT).sendKeys("me").perform();
I have the following Selenium script for opening alert on rediff.com:
public class TestC {
public static void main(String[] args) throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//*[#id='signin_info']/a[1]")).click();
driver.findElement(By.id("btn_login")).click();
Thread.sleep(5000);
Alert alert=driver.switchTo().alert();
alert.accept();
}
}
This very same script is working fine in Firefox and IE9, however using Google Chrome after opening the alert, rest of the code is not working. The main thing is that does not shows any exception, error or anything.
Please provide any solution as soon as possible.
Thanks a lot!
Note: If we need to change any setting of browser or any thing please let me know.
Selenium version:Selenium(2) Webdriver
OS:Windows 7
Browser:Chrome
Browser version:26.0.1410.64 m
I'm pretty sure your problem is a very common one, that's why i never advise using Thread.sleep(), since it does not guarantee the code will run only when the Alert shows up, also it may add up time to your tests even when the alert is shown.
The code below should wait only until some alert is display on the page, and i'd advise you using this one Firefox and IE9 aswell.
public class TestC {
public static void main(String[] args) throws InterruptedException, Exception {
System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
WebDriver driver = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(driver, 5);
driver.get("http://www.rediff.com/");
driver.findElement(By.xpath("//*[#id='signin_info']/a[1]")).click();
driver.findElement(By.id("btn_login")).click();
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
alert.accept();
}
}
Mostly all that is done here, is changing Thread.sleep(), for a condition that actually will only move forward on the code as soon a alert() is present in the page. As soon as someone does, it wil switch to it and accept.
You can find the Javadoc for the whole ExpectedConditions class here.
Unfortunately AlertIsPresent doesn't exist in C# API
http://selenium.googlecode.com/git/docs/api/dotnet/index.html
You can use something like this:
private static bool TryToAcceptAlert(this IWebDriver driver)
{
try
{
var alert = driver.SwitchTo().Alert();
alert.Accept();
return true;
}
catch (Exception)
{
return false;
}
}
public static void AcceptAlert(this IWebDriver driver, int timeOutInSeconds = ElementTimeout)
{
new WebDriverWait(driver, TimeSpan.FromSeconds(timeOutInSeconds)).Until(
delegate { return driver.TryToAcceptAlert(); }
);
}