I am new to the Selenium .
I need to check the availability of a button in the system and need to mark it pass and fail with AssertEquals.
Please help me .
#Test
public void sellercheck () throws InterruptedException
{
Thread.sleep(2000);
driver.findElement(By.id("UserEvent")).click();
//String r=Read.getvalue().get(0);
//select the seller
driver.findElement(By.id("LegacyNumberCriterion")).sendKeys("123456");
driver.findElement(By.id("SuperUse")).click();
System.out.println("seller number entered");
try
{
if(driver.findElements(By.id("OrganizationBranchId")).size()!=0)
{
driver.findElement(By.id("button1")).click();
}
else
{
System.out.println("The button is not available for the seller");
}
}
catch(NoSuchElementException e)
{
System.out.println("Element does not exist!");
}
}
You can choose from following 2 solutions which suitable to you:
1] Code to check element present or not using assertion in Selenium Webdriver would be something like this:
assertTrue(!isElementPresent(By.id("id of button")));
2] This assertion verifies that there are no matching elements in the DOM and returns the value of Zero, so the assertion passes when the element is not present. Also it would fail if it was present.
Assert.assertEquals(0, driver.findElement(By.id("id of button")).size());
Try this solution and let me know if it works.
Try this piece of code with some simple tweaks to your own code:
WebDriver driver;
#Test
public void sellercheck () throws InterruptedException
{
Thread.sleep(2000);
driver.findElement(By.id("UserEvent")).click();
//String r=Read.getvalue().get(0);
//select the seller
driver.findElement(By.id("LegacyNumberCriterion")).sendKeys("123456");
driver.findElement(By.id("SuperUse")).click();
System.out.println("seller number entered");
try
{
if(driver.findElements(By.id("OrganizationBranchId")).size()!=0)
{
driver.findElement(By.id("button1")).click();
}
else
{
System.out.println("The button is not available for the seller");
}
}catch(NoSuchElementException e)
{
System.out.println("Element does not exist!");
}
}
Let me know if this works for you or update me the error you see.
Related
I am writing a piece of code in which in the if condition I am giving a condition that if the element is displayed they only go to if part otherwise if the element is not displayed then it should go to else part. But whenever it is coming to the if condition, it searches for the element and when it doesn't find it, it gives a timeout exception. What can be done ?
public void addaddress() {
suites.setupEnviroment();
WebDriver driver = suites.getWebDriver();
try {
//code to find elements
try {
if(driver.findElement(By.xpath("//div[#class='toast lgksToast ']")).isDisplayed()){
System.out.println("fail");
}
else{
System.out.println("pass");
}
} catch (Exception e) {
System.out.println(e);
}
}catch(Exception e) {
System.out.println(e);
}
}
In the above code if element with this xpath (//div[#class='toast lgksToast ']) is not found then its not executing else part
what should i do for thid please suggest.
Thanks in advance
Use the size() method with findElements and it will start working.
if(driver.findElements(By.xpath("//div[#class='toast lgksToast ']")).size() > 0) {
System.out.println("fail");
} else {
System.out.println("pass");
}
Here i'm getting all checkboxes of a page but unable to select all check boxes when i tried below code its giving error.Here is my code
public class AllCheckBoxes {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.flipkart.com/mobiles/pr?p%5B%5D=facets.brand%255B%255D%3DSamsung&sid=tyy,4io&otracker=nmenu_sub_electronics_0_Samsung");
Thread.sleep(1000);
try {
// Option 1
List<WebElement> CHECKBOXlist = driver.findElements(By.xpath("//input[#type='checkbox']"));
// Option 2
//List<WebElement> CHECKBOXlist = driver.findElements(By.cssSelector("[type='checkbox']"));
System.out.println("Total Check Boxes are avaliable here are: "+CHECKBOXlist.size());
for (WebElement checkbox : CHECKBOXlist) {
checkbox.click();
}
} catch (Exception e) {
System.out.println(e.getMessage());
// Error as: Element is no longer attached to the DOM
// For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
}
driver.quit();
}
}
Can anybody guide me how to do this?
A stale element exception usually occurs when you are trying to interact with a web element from a previous page instance. Perhaps one of these checkboxes you are ticking does something like reload the page, if this is the case, then the remaining checkboxes to click will fail.
Edit: Yes this does seem to be the case after visiting the webpage you are trying to use in your code. My suggestion would be to use indexing within an XPath to get the checkboxes one at a time:
public class AllCheckBoxes {
public static void main(String[] args) throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://www.flipkart.com/mobiles/pr?p%5B%5D=facets.brand%255B%255D%3DSamsung&sid=tyy,4io&otracker=nmenu_sub_electronics_0_Samsung");
Thread.sleep(1000);
try {
// Option 1
List<WebElement> CHECKBOXlist = driver.findElements(By.xpath("//input[#type='checkbox']"));
// Option 2
//List<WebElement> CHECKBOXlist = driver.findElements(By.cssSelector("[type='checkbox']"));
System.out.println("Total Check Boxes are avaliable here are: "+CHECKBOXlist.size());
// this for loop will account for page loads:
for (int i = 0; i < CHECKBOXlist.size(); i++) {
driver.findElement(By.xpath("(//input[#type='checkbox'])[" + (i+1) + "]")).click();
}
} catch (Exception e) {
System.out.println(e.getMessage());
// Error as: Element is no longer attached to the DOM
// For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
}
driver.quit();
}
}
So basically, you're going to have to find the checkboxes individually rather than all at once to account for page reloading.
While executing the code when the webelement "err" is null then webdriver taking too much time for executing the if block but "err" is not null webdriver going to the else block and driver getting closed then ok
driver.findElement(By.id("UHID")).sendKeys("1234440");
driver.findElement(By.id("btnSubmit")).click();
Thread.sleep(100);
WebElement err=null;
try
{
err=driver.findElement(By.xpath("//*[#id='Error']/div/p"));
}
catch(NoSuchElementException e)
{
System.out.println("No Such Element Exception.");
}
if(!(err != null && err.isDisplayed()))
{
Thread.sleep(100);
Select policytype=new Select(driver.findElement(By.id("PolicyType")));
policytype.selectByVisibleText("Corporate");
//Select Payer
Thread.sleep(200);
driver.findElement(By.id("Payer")).sendKeys(Keys.TAB);
//Payer
Select Payer=new Select(driver.findElement(By.id("Payer")));
Payer.selectByIndex(1);
driver.findElement(By.id("Submit")).click();
}
else
{
System.out.println("UHID Not Exist");
driver.close();
}
please advise
thanks in advance
try this:
try
{
driver.manage().timeouts().implicitlyWait(1000, TimeUnit.MILLISECONDS);
err=driver.findElement(By.xpath("//*[#id='Error']/div/p"));
}
catch(NoSuchElementException e)
{
//Log your error
}
finally
{
driver.manage().timeouts().implicitlyWait(15000, TimeUnit.MILLISECONDS);
}
This will tell the driver to only take 1 second to search for the "err" element before throwing an exception. It will also reset the implicit wait, even in the event of an exception.
I have developed a s keyword driven framework. It has a action keyword to switch the frame.
It works fine with Mozilla. But when it comes to IE it is not switching. It logs error.
IE driver -IEDriverServer_x64_2.44.0
IE version -9
Selenium version -selenium-java-2.44.0
Thanks in advance.
public static void switchFrame(String object,String data)throws Exception{
try{
driver.switchTo().frame("Ifrm");
Log.info("Switched the frame");
}
catch(Exception e){
Log.error("Not able to switch the frame--- " + e.getMessage());
DriverScript.bResult = false;
}
}
Here exception occurs.
I assume, the value you specified in frame is id/name/etc. You have to access the frame by calling the driver with specified value. Code would be
driver.switchTo().frame(driver.findElement(By.id("Ifrm")));
Selenium won't let me switch to the iframe by ID on Internet Explorer, but it does allow me to switch by index. If you have some sort of property that you can check that it is only available on the iframe you can do the following
new WebDriverWait(driver, 5).until(
new Predicate<WebDriver>() {
#Override
public boolean apply(WebDriver input) {
try {
int i = 1;
while (true) {
driver.switchTo().defaultContent();
driver.switchTo().frame(i);
String aClass =
driver.findElement(By.xpath("/html/body"))
.getAttribute("class");
if (aClass.contains("modal")) {
return true;
}
++i;
}
} catch (NoSuchFrameException e) {
return false;
}
}
}
);
In my case I was looking for a body class of modal
Hi can anyone pls solve this. When i write a code to automate sometimes the elements are not identified and sometimes its not found even they are present, means even if the id is present it says element not found error. So I a trying to create a method where i would pass all the dom objects i find like Ex :
public static void Click(WebDriver driver, String name,Sting linktext,Sting id,Sting Xpath,String css)
{
driver.findElement(new ByAll(By.name(name),
By.linkText(linktext),
By.id(id),
By.xpath(xpath),
By.cssSelector(css))).click();
}
And i would pass what ever value i find in source page like sometimes it will have oly id or it ll have oly link text Ex:(when i import this method in other class)
Click(Webdriver driver, "username",null,"","//[fas].user");
is this the correct way to pass the arguments. can i pass like null and "" (blank). Pls help this would become a one simple effective framework for me.
you can use this 2 methods
public static WebElement findElement(WebDriver driver, By selector, long timeOutInSeconds) {
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.presenceOfElementLocated(selector));
return findElement(driver, selector);
}
public static WebElement findElementSafe(WebDriver driver, By selector, long timeOutInSeconds) {
try {
return findElement(driver, selector, timeOutInSeconds);
} catch (TimeoutException e) {
return null;
}
}
public static void waitForElementToAppear(WebDriver driver, By selector, long timeOutInSeconds, String timeOutMessage) {
try {
WebDriverWait wait = new WebDriverWait(driver, timeOutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(selector));
} catch (TimeoutException e) {
throw new IllegalStateException(timeOutMessage);
}
}
----------------
public static void click(WebDriver driver , By ... selector ){
for (By byPath : selector) {
WebElement element = findElementSafe(driver, byPath, 1);
if(element != null){
element.click();
}
}
}