TESTEVERYTHING

Showing posts with label Selenium. Show all posts
Showing posts with label Selenium. Show all posts

Sunday, 5 February 2017

EXTRACT CSS PROPERTY VLAUE OF PSEUDO ELEMENTS CONTAINING :after/:before CSS TAG USING JAVASCRIPT IN WEBDRIVER :

We cannot extract css properties of pseudo elements using web driver commands such as ‘.getPropertyValue’ . For this, we need to use JavaScript and execute a js script in selenium web driver.


A CSS pseudo-element is used to style specified parts of an element.
   For example, it can be used to:
   Style the first letter, or line, of an element
   Insert content before, or after, the content of an element

ISSUE:



In above scenario, we need to get the text “Internal Use Only” from UI which is associated with an Anchor (a) tag in DOM with :after CSS tag. The text is present in “content” Style Property as shown in right highlighted box.

The :after CSS tag cannot be located directly using web driver and thus required text cannot be retrieved simply by using .getPropertyValue() function in selenium.

To achieve this, a javascript needs to be executed in our selenium code :

WebElement elementObj = driver.findElement(By.xpath("<YourXpath>"));
String pseudoElementText = ((JavascriptExecutor)driver).executeScript("return window.getComputedStyle(arguments[0],':after').getPropertyValue(content');", elementObj).toString();

System.out.println(pseudoElementText);


In same way we can extract another properties values as well.

Thanks


Wednesday, 16 November 2016

Actual differences between Explicit and Implicit Waits

Hi All,

As i have already mentioned the differences Explicit and Implicit Waits in my earlier post but now we will see the actual results. there will be two conditions we can think of it what will happen if implicit wait is greater than explicit wait OR  implicit wait is lower than explicit wait

lets see what will happen


Condition 1: implicit wait is greater than explicit wait

           implicitlyWait = 10 seconds
            explicitWait = 2 seconds
            ///////////////////////////////////////
            public static void main(String[]args) {
            FirefoxDriver driver = new FirefoxDriver();
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
            driver.get("https://www.google.com");
            try {
                        Date date = new Date();
                        System.out.println(" before " + new Timestamp(date.getTime()));
                        WebDriverWait wait = new WebDriverWait(driver, 2);
                        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[contains(text(),'NOT FOUND ELEMENT')]")));
            } catch (Exception e) {
                        // TODO Auto-generated catch block
                        Date date = new Date();
                        System.out.println(" after " + new Timestamp(date.getTime()));
                        e.printStackTrace();
            }


/////////////////////////////////

let see the output in console:   taking 10 seconds

before 2016-11-16 16:24:33.128
after 2016-11-16 16:24:43.321

Condition 2: implicit wait is lower than explicit wait
           implicitlyWait = 2 seconds
            explicitWait = 10 seconds
            ///////////////////////////////////////
            public static void main(String[]args) {
            FirefoxDriver driver = new FirefoxDriver();
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
            driver.get("https://www.google.com");
            try {
                        Date date = new Date();
                        System.out.println(" before " + new Timestamp(date.getTime()));
                        WebDriverWait wait = new WebDriverWait(driver, 10);
                        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[contains(text(),'NOT FOUND ELEMENT')]")));
            } catch (Exception e) {
                        // TODO Auto-generated catch block
                        Date date = new Date();
                        System.out.println(" after " + new Timestamp(date.getTime()));
                        e.printStackTrace();
            }


/////////////////////////////////

let see the output in console:   taking 10 seconds

before 2016-11-16 16:26:53.355
 after 2016-11-16 16:27:03.53

Thursday, 10 November 2016

Webdriver/Selenium Difference between methods .isDisplayed() and .isEnabled()?

Hi All,
I have seen so many posts where people asked the differences between .isDisplayed() and .isEnabled() in Selenium/Webdriver automation and found mostly people are still confused.
The methods .isDisplayed() and .isEnabled() have nothing in common.
 Here I am trying to explain the read differences between .isDisplayed() and .isEnabled(). As name itself clearly says .isDisplayed() means is my object are visible or not on my webpage means Am I able to see my element through my eyes.


Method .isDisplayed() :


An element is considered displayed when it is perceptually visible to the human eye.
The element displayed algorithm is a boolean state where true signifies that the element is displayed and false signifies that the element is not displayed.

To compute the state on element:
  • ·         If the attribute hidden is set, return false.
  • ·         If the computed value of the display style property is "none", return false.

Like
<input type="hidden" name="abc" value="10" id="hiddenFiled1" />

Observe the output, since element with id hiddenField1 is hidden from web page, so isDisplayed method return false, whereas isEnabled() method return true.



OR

Refer below link


Try to run with display: block;  and display: none;




Method .isEnabled() :


An element is considered enabled if it's not a form control (button, input, textarea, select or option) or when the user interactions and focus are not blocked with the disabled attribute/property.
Is Element Enabled determines if the referenced element is enabled or not. This operation only makes sense on form controls.

Like
Last name: <input type="text" name="lname" disabled><br>













Last name: <input type="text" name="lname" enabled><br>


 
Refer below link


Last name: <input type="text" name="lname" disabled><br>



Sunday, 3 July 2016

Scroll the WebGrid using selenium webdriver

Hi,

Sometimes in webpage there is web table grid present on page and we need to scroll the grid to access the element information. Because of asynchronous call data will not load completely until unless you scroll the grid.

From wiki..

Synchronous means that you call a web service (or function or whatever) and wait until it returns - all other code execution and user interaction is stopped until the call returns. Asynchronous means that you do not halt all other operations while waiting for the web service call to return
Here I have written the method that will scroll your grid until it reach to end of data row.

Note: ElementXpath will be your data table rows xpath
like  ElementXpath = "//table//tr";



public static void ScrollView(WebDriver driver,String ElementXpath) throws

Exception {

int elemntCountBeforeScroll= driver.findElements(By.xpath(ElementXpath)).size();

if (elemntCountBeforeScroll>0){


WebElement element = driver.findElements(By.xpath(ElementXpath)).get(elemntCountBeforeScroll-1);

JavascriptExecutor jse = (JavascriptExecutor) driver;

jse.executeScript("arguments[0].scrollIntoView(true);", element);

Thread.sleep(8000);


int elemntCountAfterScroll= driver.findElements(By.xpath(ElementXpath)).size();

for (int i = 0; i < elemntCountBeforeScroll; i++) {
if(elemntCountAfterScroll>elemntCountBeforeScroll)
{ elemntCountBeforeScroll = elemntCountAfterScroll;
 element = driver.findElements(By .xpath(ElementXpath)).get(elemntCountAfterScroll-1);
 jse = (JavascriptExecutor) driver;
 jse.executeScript("arguments[0].scrollIntoView(true);", element); 
Thread.sleep(8000);
elemntCountAfterScroll = driver.findElements(By .xpath(ElementXpath)).size(); }
}
}
}

Wednesday, 17 June 2015

Difference between action.build().perform() and action.perform()


In Webdriver, handling keyboard events and mouse events (including actions such as Drag and Drop or clicking multiple elements With Control key) are done using the advanced user interactions API . It contains Actions and Action classes which are needed when performing these events. In order to perform action events, we need to use org.openqa.selenium.interactions.Actions class.

The build() method is used compile all the listed actions into a single step.
we have to use build() when we are performing sequence of operations and no need to use only if we are performing single action.

example where build() required
Actions builder = new Actions(driver);
builder.clickAndHold((WebElement)listItems.get(0)).clickAndHold((WebElement)listItems.get(3)).click().build().perform();


in the above code we are performing more than one operations so we have to use build() to compile all the actions into a single step

example where build is not required

WebElement draggable = driver.findElement(By.id("draggable")); 
WebElement droppable = driver.findElement(By.id("droppable")); 
new Actions(driver).dragAndDrop(draggable, droppable).perform();
in the above code we are performing just a single operations so no need to use build()

Monday, 22 September 2014

How to handle login pop up window using Selenium WebDriver?

Hi All,

Some times while using webdriver we have to face login popup handle.  When we passing the url using webdriver.get or webdriver.navigate.to("URL") at this time browser asks for login credentials.
For handle this situation we have to do following things.

1. HTTP Basic Authentication with Selenium WebDriver

the authentication prompt is not available from the Selenium WebDriver. One of the way to handle this limitation is to pass user and password in the url like like below:


         http://username:password@the-site.com
So just to make it more clear. The username is username password is password and the rest is usual URL of your test web

        WebDriver driver = getDriver();
        String URL = "http://" + username + ":" + password + "@" + "link";
        driver.get(URL);
but sometimes it does not work for IE browser
 we can use robot  method


import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;

import org.openqa.selenium.Alert;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class FillAuthAlert {
 private static final String MY_URL = "https://myurl.com";
 private static final String USERNAME= "myuser";
 private static final String PASSWORD= "mypass";
 
 public static void main(String[] args) throws Exception {

  WebDriver driver = new FirefoxDriver();
  driver.get(MY_URL);
  Alert alert = driver.switchTo().alert();
  Robot robot = new Robot();
  Thread.sleep(1000);
  type(robot, USERNAME);
  robot.keyPress(KeyEvent.VK_TAB);
  robot.keyRelease(KeyEvent.VK_TAB);
  Thread.sleep(1000);
  type(robot, PASSWORD);
  alert.accept();
 }
 
 public static void type(Robot robot, String characters) {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        StringSelection stringSelection = new StringSelection( characters );
        clipboard.setContents(stringSelection, null);

        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyPress(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_V);
        robot.keyRelease(KeyEvent.VK_CONTROL);
    }
}

Wednesday, 9 January 2013

Perform Mouse, drag-and-drop, sliding, selecting multiple Action in Webdriver/Selenium 2

Perform Mouse, drag-and-drop, sliding, selecting multiple Actions in Web driver/Selenium 2 

Solution

The example code below shows some examples where we can use the Actions interface of Selenium WebDriver.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package selenium2.examples;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class ActionExample {
    private static WebDriver driver;

    @BeforeClass
    public void setUp() {
        driver = new FirefoxDriver();
    }

    @AfterClass
    public void tearDown() {
        driver.close();
        driver.quit();
    }

    @Test
    public void draggable() {
        driver.get("http://jqueryui.com/demos/draggable/");

        WebElement draggable = driver.findElement(By.id("draggable"));
        new Actions(driver).dragAndDropBy(draggable, 120, 120).build()
                .perform();
    }

    @Test
    public void droppable() {
        driver.get("http://jqueryui.com/demos/droppable/");

        WebElement draggable = driver.findElement(By.id("draggable"));
        WebElement droppable = driver.findElement(By.id("droppable"));
        new Actions(driver).dragAndDrop(draggable, droppable).build().perform();
    }

    @Test
    public void selectMultiple() throws InterruptedException {
        driver.get("http://jqueryui.com/demos/selectable/");

        List<WebElement> listItems = driver.findElements(By
                .cssSelector("ol#selectable *"));

        Actions builder = new Actions(driver);
        builder.clickAndHold(listItems.get(1)).clickAndHold(listItems.get(2))
                .click();

        Action selectMultiple = builder.build();
        selectMultiple.perform();
    }

    @Test
    public void sliding() {
        driver.get("http://jqueryui.com/demos/slider/");

        WebElement draggable = driver.findElement(By
                .className("ui-slider-handle"));
        new Actions(driver).dragAndDropBy(draggable, 120, 0).build().perform();
    }
}

Friday, 12 October 2012

Maximize window in selenium/webdriver

By using below methods you maximize window in selenium/webdriver
1.  selenium.windowMaximize();
2.  driver.manage().window().maximize();

3. If above 2 commands doesn't work try the below code.

Refer the below example

Sunday, 23 September 2012

Locating elements using DOM, Css and Xpath

 Refer the below example

Whole web page

xpath=/html
css=html
document.documentElement
Whole web page body
xpath=/html/body
css=body
document.body
All text nodes of web page
//text()
Element <E> by absolute reference
xpath=/html/body/.../.../.../E
css=body>…>…>…>E
document.body.childNodes[i]...childNodes[j]
Element <E> by relative reference
//E
css=E
document.gEBTN('E')[0]
Second <E> element anywhere on page
xpath=(//E)[2]
document.gEBTN('E')[1]
Image element
//img
css=img
document.images[0]
Element <E> with attribute A
//E[@A]
css=E[A]
dom=for each (e in document.gEBTN('E')) if (e.A) e Œ
Element <E> with attribute A containing text 't' exactly
//E[@A='t']
css=E[A='t'] 
Element <E> with attribute A containing text 't'
//E[contains(@A,'t')]

Element <E> whose attribute A begins with 't'
//E[starts-with(@A, 't')]

Element <E> whose attribute A ends with 't'
//E[substring(@A, string-length(@A) - string-length('t')+1)='t']

Element <E> with attribute A containing word 'w'
//E[contains(concat('⦿', @A, '⦿'), '⦿w⦿')
Element <E> with attribute A matching regex ‘r’
Element <E1> with id I1 or element <E2> with id I2
//E1[@id=I1] | //E2[@id=I2]
css=E1#I1,E2#I2
Element <E1> with id I1 or id I2
//E1[@id=I1 or @id=I2]
css=E1#I1,E1#I2
Attribute A of element <E>
//E/@A {Se: //E@A }
{Se: css=E@A }
document.gEBTN('E')[0].getAttribute('A')
{Se: document.gEBTN('E')[0]@A }
Attribute A of any element
//*/@A  {Se: //*@A }
{Se: css=*@A }
Attribute A1 of element <E> where attribute A2 is 't' exactly
//E[@A2='t']/@A1 {Se: //E[@A2='t']@A1 }
{Se: css=E[A2='t']@A1 }
Attribute A of element <E> where A contains 't'
//E[contains(@A,'t')]/@A {Se: //E[contains(@A,'t')]@A }
{Se: @A }
Element <E> with id I
//E[@id='I']
css=E#I
Element with id I
//*[@id='I']
css=#I
document.gEBI('I')
id=I

Which one is right ?

Translate







Tweet