Selenium Advanced Applications

Source: Internet
Author: User


For this paragraph is quite feeling, just want to say, the code still need to knock on their own. 1. Change the user agent

Import Org.junit.AfterClass;
Import Org.junit.BeforeClass;
Import Org.junit.Test;
Import Org.openqa.selenium.WebDriver;
Import Org.openqa.selenium.firefox.FirefoxDriver;

Import Org.openqa.selenium.firefox.FirefoxProfile;

	public class Proxytest {static Webdriver driver;
		@BeforeClass public static void Beforeclass () {//proxy IP and port String proxyip= "192.168.12.0";
		int proxyport=80;
		Firefoxprofile profile=new firefoxprofile ();
		Use of proxy profile.setpreference ("Network.proxy.type", 1);
		Configure the HTTP proxy: (N) profile.setpreference ("Network.proxy.http", Proxyip);
		Profile.setpreference ("Network.proxy.http_prot", ProxyPort);
		Select the use the same agent for all protocols (S) marquee profile.setpreference ("Network.proxy.share_proxy_settings", true);
		Configure the "Do not use proxy: (N)" text box profile.setpreference ("network.proxy.no_proxies_on", "localhost, 127.0.0.1");
	To agent the way to start Firefox driver=new firefoxdriver (profile);
	@Test public void Test () {driver.get ("http://www.baidu.com"); @AfterClass public static void AfterclaSS () {//driver.quit (); }
}

After running, view the proxy settings on the Open Firefox (option-> advanced-> Network-> connection-> settings), as shown below:


Friendship tip: After testing must be changed back. The default is "Use System Agent settings." 2. Read Cookies

Add Cookies:

Cookie cookie = new Cookie ("Key", "value");

Driver.manage (). Addcookie (cookie);

Get the value of the cookie:

set<cookie> allcookies = Driver.manage (). GetCookies ();

Gets the value of a cookie based on the name of a cookie:

Driver.manage (). getcookienamed ("CookieName");

To delete a cookie:

Driver.manage (). deletecookienamed ("CookieName");

Driver.manage (). Deletecookie (Loadedcookie);

Driver.manage (). Deleteallcookies ();

Here is an example:

Import Java.util.Set;
Import Org.junit.After;
Import Org.junit.Before;
Import Org.junit.Test;
Import Org.openqa.selenium.Cookie;
Import Org.openqa.selenium.WebDriver;

Import Org.openqa.selenium.firefox.FirefoxDriver;
	
	public class CookieTest {Webdriver driver;
	@Before public void SetUp () throws Exception {driver=new firefoxdriver ();
	@After public void teardown () throws Exception {driver.quit ();
		@Test public void Test () {Printcookie ();
		Add a cookie Cookie Cookie=new cookie ("s", "Selenium");
		Driver.manage (). Addcookie (cookie);
		Printcookie ();	Deletes a cookie driver.manage (). Deletecookie (cookie);
	Driver.manage (). deletecookienamed ("s") or Printcookie ();
		
		public void Printcookie () {//Get and print all Cookies set<cookie> allcookies=driver.manage (). GetCookies ();
		System.out.println ("----------Begin---------------");
		for (Cookie c:allcookies) {System.out.println (String.Format ("%s->%s", C.getname (), C.getvalue ())); } System.out.println ("----------End---------------"); }
}

The results of the operation appear as follows:

----------Begin---------------
----------End---------------
----------Begin---------------
S->selenium
----------End---------------
----------Begin---------------
----------End---------------
You can see that the system's cookie is empty until the cookie is added. The cookie (S,selenium) was successfully added and finally successfully deleted. 3. Invoke Java Script

Selenium provides a executescript, executeasyncscript two methods to handle the problem of JS calls. Where Executescript is a synchronous method, using it to execute JS code will block the main thread execution until the JS code executes; The Executeasyncscript method is an asynchronous method that does not block execution of the main thread.

Import Org.junit.Test;
Import Org.openqa.selenium.WebDriver;
Import Org.openqa.selenium.firefox.FirefoxDriver;
Import Org.openqa.selenium.JavascriptExecutor;

public class Jstest {
	@Test the public
	void Test () {
		webdriver driver=new firefoxdriver ();
		Driver.get ("http://www.baidu.com");
		Javascriptexecutor js= (javascriptexecutor) driver;
		Js.executescript ("document.getElementById" ("kw\"). Value=\ "selenium\");
        Use JS code to get Baidu search box text
        String keyword = (string) (Js.executescript ("var input = document.getElementById (\" kw\). Value;return input "));
        SYSTEM.OUT.PRINTLN (keyword);
        Driver.quit ();
	}

Run Result:

Selenium
4. Webdriver screenshot

Import Java.io.File;
Import java.io.IOException;
Import Org.apache.commons.io.FileUtils;
Import Org.junit.Test;
Import Org.openqa.selenium.OutputType;
Import Org.openqa.selenium.TakesScreenshot;
Import Org.openqa.selenium.WebDriver;

Import Org.openqa.selenium.firefox.FirefoxDriver;
		public class Screenshottest {@Test the public void Test () {webdriver driver=new firefoxdriver ();
		Driver.get ("http://www.baidu.com");
		Screenshot ("Selenium.jpg", (takesscreenshot) driver);
	Driver.quit ();
		public static void screenshot (String name,takesscreenshot driver) {string Savapath=system.getproperty ("User.dir");
		File Sourcefile=driver.getscreenshotas (Outputtype.file);
			try{System.out.println ("Begin Saving screenshot to Path:" +savapath);
		Fileutils.copyfile (SourceFile, New File (savapath+ "\" +name));
			catch (IOException e) {System.out.println ("Save screenshot failed!");
		E.printstacktrace ();
		} finally{System.out.println ("Finish screenshot!"); }
	}
}

Run Result:

Begin Saving screenshot to Path:d:\workspace_luna\seleniumdemo
Finish screenshot!

Because Eclipse's workspace is different, it causes the path above to be different. But it doesn't matter, we open the corresponding path can see selenium.jpg. Open after Baidu is the home page screenshot.
5. Page Wait

Because the load page takes a while, if the page has not finished loading to find elements, it is inevitable to find. The best way to do this is to set a default wait time and wait for a few minutes to find the page element if you can't find it until it times out. Webdriver provides two methods, one is explicit wait, the other is recessive wait.

Dominant wait:

Show wait is clear to wait for an element to appear or a certain element of the clickable and so on, and so on, and so on, unless within the specified time is not found, then jump out of the exception.

New Webdriverwait (Driver). Until (Expectedconditions.presenceofelementlocated (by.id ("kw"));

Of course, you can rewrite the inner class yourself:

Webelement e = (new webdriverwait (Driver)). Until (
	    new expectedcondition< webelement> () {
	        @Override Public
	        webelement Apply (Webdriver D) {return
	            d.findelement (By.linktext ("Selenium_ Baidu Encyclopedia");
	        }
	    );

The following example is: Open Baidu, search "Selenium", waiting for the search results appear "selenium_ Baidu Encyclopedia" when clicked on the link.

Import Org.junit.Test;
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.ExpectedCondition;
Import org.openqa.selenium.support.ui.ExpectedConditions;

Import org.openqa.selenium.support.ui.WebDriverWait;
		public class Explicitwaittest {@Test the public void Test () {webdriver driver=new firefoxdriver ();
		Driver.get ("http://www.baidu.com");
		Driver.findelement (By.id ("kw")). SendKeys ("Selenium");
		Driver.findelement (By.id ("su")). Click (); Method one//new webdriverwait (driver,10). Until (Expectedconditions.presenceofelementlocated (By.linktext ("Selenium_
		Baidu Encyclopedia "));
		Driver.findelement (By.linktext ("Selenium_ Baidu Encyclopedia")). Click ();
			        Method two Webelement e = (new webdriverwait (Driver)). Until (new expectedcondition< webelement> () { @Override public webelement apply (Webdriver D) {return d.findelement by.LinkText ("Selenium_ Baidu Encyclopedia"));
		}
			    }
			);
		
		E.click ();
	Driver.quit (); }
}

Running words are passed, but if the middle does not show waiting, direct lookup will fail.

Hidden wait:

Stealth wait just for a while, the element does not have to appear, as long as the time will continue to execute.

Driver.manage (). Timeouts (). Implicitlywait (second, timeunit.seconds);

Or the above example, with the implicit waiting to write is:

Import Java.util.concurrent.TimeUnit;
Import Org.junit.Test;
Import Org.openqa.selenium.By;
Import Org.openqa.selenium.WebDriver;
Import Org.openqa.selenium.firefox.FirefoxDriver;

public class Implicitwaittest {
	@Test the public
	void Test () {
		webdriver driver=new firefoxdriver ();
		Driver.get ("http://www.baidu.com");
		Driver.findelement (By.id ("kw")). SendKeys ("Selenium");
		Driver.findelement (By.id ("su")). Click ();
		Driver.manage (). Timeouts (). implicitlywait (5, timeunit.seconds);
		Driver.findelement (By.linktext ("Selenium_ Baidu Encyclopedia")). Click ();
		
		Driver.quit ();
	}
The run result is still passed. But I think it looks like a stupid way to "thread.sleep ()" Almost, but not much more efficient than it.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.