Monday, 26 August 2013

Selenium Basics & Tips


1| Maximize Firefox browser window using selenium webdriver

WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();

#PYTHON
driver.maximize_window()

#RUBY
require "selenium-webdriver"
@driver.manage.window.maximize



2| Customize browser window size

driver.manage().window().setSize(new Dimension(320, 480));

#PYTHON
driver.set_window_size(1920, 500)

#RUBY
@driver.manage.window.resize_to(300,700)



3| Get current web page URL

System.out.println(driver.getCurrentUrl());

#PYTHON
print driver.current_url

#RUBY
puts @driver.current_url



4| Navigate Back | Forward & Page refresh

Navigate Back
Webdriver driver = new FirefoxDriver();
driver.navigate().back();
or|
Actions actions = new Actions(driver);
actions.sendKeys(Keys.BACK_SPACE).perform();

#PYTHON
driver.back()

#RUBY
@driver.navigate.back


Navigate Forward
driver.navigate().forward();

#PYTHON
driver.forward()

#RUBY
@driver.navigate.forward


Navigate URL
driver.navigate().to("https://www.google.co.in/");

#RUBY
@driver.navigate.to "https://www.google.co.in/"


Page Refresh
driver.navigate().refresh();
or|
Actions actions = new Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();
or|
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("history.go(0)");
or|
driver.navigate().to(driver.getCurrentUrl());
or|
driver.findElement(By.id("firstname-placeholder")).sendKeys("\uE035");
or|
driver.findElement(By.id("filter-box")).sendKeys(Keys.F5);

#PYTHON
driver.refresh()

#RUBY
@driver.navigate.refresh




5| Highlighting Elements

WebElement element1 = driver.findElement(By.className("Value"));
WebElement element2 = driver.findElement(By.id("Value"));
JavascriptExecutor jse = (JavascriptExecutor)driver; 
jse.executeScript("arguments[0].setAttribute('style', arguments[1]);", element1, "color: blue; border: 2px solid blue;");
jse.executeScript("arguments[0].setAttribute('style', arguments[1]);", element2, "color: yellow; border: 0px solid red;");

Excercise|1|
@Test
public void highlighttest() throws Exception {
driver.get("www.whatever.com");
WebElement searchbutton = driver.findElement(By.id("Value"));
highlightElement(searchbutton);
WebElement submitbutton = driver.findElement(By.id("Value"));
highlightElement(submitbutton);
element.click();
}

public void highlightElement(WebElement element) {
for (int i = 0; i < 2; i++) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 2px solid yellow;");
js.executeScript("arguments[0].setAttribute('style', arguments[1]);", element, "");
}



6| Multi-Select Elements

Excercise|1|
@Test
public void Multiselect() throws Exception {

driver.get("http://www.ryancramer.com/journal/entries/select_multiple/");

List<WebElement> ele = driver.findElements(By.tagName("select"));
System.out.println(ele.size());
WebElement ele2 = ele.get(0);

List<WebElement> ele3 = ele2.findElements(By.tagName("option"));
System.out.println(ele3.size());

ele2.sendKeys(Keys.CONTROL);
ele3.get(0).click();
ele3.get(1).click();
ele3.get(3).click();
ele3.get(4).click();
ele3.get(5).click();
}


7| Double-click WebElement

Actions action = new Actions(driver); 
action.doubleClick(driver.findElement(By.id("Value"))); 
action.perform();



8| Delete All Cookies

driver.manage().deleteAllCookies();



9| Shortcut to open IDE in the same screen

Ctrl + shift + S






10| Open a New Tab

driver.findElement(By.id("Value")).sendKeys(Keys.CONTROL + "t");
or|
Robot r = new Robot();
r.keyPress(KeyEvent.VK_CONTROL);
r.keyPress(KeyEvent.VK_T);



11| Open a New Window

@Test
public void Test01() throws Exception {
openTab("http://www.xyz.com");
}

public void trigger(String script, WebElement element) {
((JavascriptExecutor) driver).executeScript(script, element);
}

public Object trigger(String script) {
return ((JavascriptExecutor) driver).executeScript(script);
}

public void openTab(String url) {
String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";
Object element = trigger(String.format(script, url));
if (element instanceof WebElement) {
WebElement anchor = (WebElement) element;
anchor.click();
trigger("var a=arguments[0];a.parentNode.removeChild(a);", anchor);
} else {
throw new JavaScriptException(element, "Unable to open Window", 1);
}
}




12| Select Dropdown Box

driver.get("http://www.angelfire.com/fl5/html-tutorial/ddmenu.htm");
Select dropdown = new Select(driver.findElement(By.name("jump")));
dropdown.selectByIndex(1);

Select has more options to play with; Some of the main functions are given below,

dropdown.deselectAll(); // Used while handling multi-select
dropdown.selectByVisibleText("");
dropdown.selectByValue("");
dropdown.deselectByIndex(3);
dropdown.deselectByValue("3");
dropdown.deselectByVisibleText("");



13| Starting Selenium Server

Open cmd. Go to server location and paste the below
$ java -jar selenium-server-standalone-<version-number>.jar



14| All Old versions of IDE available on:

http://release.seleniumhq.org/selenium-ide/


17| Selenium Release Notes [Change_Log]

Check my answer on Stackoverflow:
http://stackoverflow.com/questions/18609557/where-to-find-selenium-webdriver-release-notes/22243556#22243556



18| Right-click WebElement

Actions builder = new Actions(driver);
Action rightClick = builder.contextClick(driver.findElement(By.id("Value"))).build();
rightClick.perform();


Note:-  There will be frequent updates in this section, 'Selenium Basics & Tips'.
#Please comment your thoughts and the topics you need in this blog.

24 comments:

  1. Hi Prashanth,

    All your topics on selenium was good even a beginner can learn easily through your blog.

    I have a question many ppl says it is difficult to automate ajax application using Selenium webdriver. is it true or if it is possible to automate ajax application, can you teach me how to automate ajax application?

    Thanks in advance

    ReplyDelete
    Replies
    1. Thanks for the request. If you need any help, please send further details on seleniumworks@gmail.com
      Cheers!!

      Sams

      Delete
  2. Hi
    Prashanth sams
    can u please post how we can work with appium?
    Thanks in advance.

    ReplyDelete
    Replies
    1. Thanks Srini.
      I will have Appium sooner in this blog.
      Cheers!!

      Sams

      Delete
    2. Hi Srini,
      please refer this link for Appium
      http://seleniumworks.blogspot.in/2013/12/appium-native-ios-app-testing-webdriver.html

      Cheers!
      Sams

      Delete
  3. Hi Prashant,
    I wish to zoom out the chrome browser. I have tried with following code
    driver.findElement(By.tagName("html")).sendKeys(Keys.chord(Keys.CONTROL, Keys.SUBTRACT));
    It works fine with firefox webdriver. But Chrome webdriver throws the following Exception
    org.openqa.selenium.WebDriverException: unknown error: cannot focus element
    Please help me.

    ReplyDelete
  4. How to open new tab in chrom using selenium-webdriver in python?

    ReplyDelete
  5. i tried the following bt nt worked.
    ActionChains(self.driver).send_keys(Keys.CONTROL + "t").perform()
    # actions = ActionChains(self.driver)
    # home_link = self.driver.find_element_by_tag_name("body")
    # actions.move_to_element(home_link)
    # actions.send_keys(Keys.CONTROL+ 't')
    # actions.click(home_link)
    # actions.perform()

    # body = self.driver.find_element_by_tag_name("body")
    #
    # body.send_keys(Keys.CONTROL + 't')

    ReplyDelete
  6. Hi all,

    I am trying to zoom in on browser to 140%, any help would be greatly appreciated.

    ReplyDelete
  7. Meant to say using Ruby.

    ReplyDelete
  8. It’s the best time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I want to suggest you few interesting things or suggestions.You can write next articles referring to this article. I desire to read even more things about it..

    Selenium Training in Chennai

    ReplyDelete
  9. What you have written in this post is exactly what I have experience when I first started my blog.I’m happy that I came across with your site this article is on point,thanks again and have a great day.Keep update more information.
    Selenium Training in Chennai

    ReplyDelete
  10. Great blog..

    Thanks for Sharing this useful information amazing blog, It's help to know about the Selenium Certification and importance ofSelenium ...

    ReplyDelete
  11. I found this informative and interesting blog so i think so its very useful and knowledge able.I would like to thank you for the efforts you have made in writing this article.
    python course institute in bangalore
    python Course in bangalore
    python training institute in bangalore

    ReplyDelete
  12. All are saying the same thing repeatedly, but in your blog I had a chance to get some useful and unique information, I love your writing style very much, I would like to suggest your blog in my dude circle, so keep on updates.

    Data Science training in chennai
    Data Science training in OMR
    Data Science training in chennai
    Data Science Training in Chennai
    Data Science training in Chennai
    Data Science training in anna nagar

    ReplyDelete
  13. Whoa! I’m enjoying the template/theme of this website. It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and visual appeal. I must say you’ve done a very good job with this.
    aws training in bangalore
    RPA Training in bangalore
    Python Training in bangalore
    Selenium Training in bangalore
    Hadoop Training in bangalore

    ReplyDelete