PhantomJS Example

PhantomJS is another headless browser besides HtmlUnit. It is light weight and faster. This article will show you how to use it step by step.

Preparation For Using PhantomJS

  1. Add selenium-server-standalone-3.5.3.jar in Eclipse java project build path.
    add selenium 3.5.3 jar in java project build path
  2. Click download PhantomJS to go to PhantomJS browser executable file download page to get related version.
    download phantomjs executable file
  3. After download, extract the zip file to a local folder such as C:\WorkSpace\dev2qa.com\Lib\phantomjs-2.1.1-windows
  4. Goto PhantomJS driver download page and get the driver jar file directly.
    phantomjs driver download page
  5. Add phantomjsdriver-1.1.0.jar in Eclipse java project build path also.
    phantomjs jar file in eclipse java project build path

PhantomJS Driver Example Java Code

This example code will use PhantomJS driver to open PhantomJS headless browser. It will browse yahoo.com, input search keyword in search text box and parse out the search result list data in the result page.

Please Note: After you create PhantomJS driver, you must maximize it, other wise it will not return web elements when you use driver.findElements(  ) by XPath.

public class TestPhantomjsDriver {

	public static void main(String[] args) {


		TestPhantomjsDriver example = new TestPhantomjsDriver();
		
		example.runPhantomjsWebDriver();
		
	}

	public void runPhantomjsWebDriver()
	{
		try
		{
			// Set executable file path to system variable phantomjs.binary.path's value.
			String phantomjsExeutableFilePath = "C:/WorkSpace/dev2qa.com/Lib/phantomjs-2.1.1-windows/bin/phantomjs.exe";
			System.setProperty("phantomjs.binary.path", phantomjsExeutableFilePath);		
	       
			// Initiate PhantomJSDriver.
			WebDriver driver = new PhantomJSDriver();	
			
			/* If you want to see the browser action, you can uncomment this block of code to use Chrome.
			// Specify Chrome Driver executable file path.
		    String chromeDriverPath = "C:\\Workspace\\dev2qa.com\\Lib\\chromedriver_win32\\chromedriver.exe";
			 
			//Assign chrome driver path to system property "webdriver.chrome.driver"
			System.setProperty("webdriver.chrome.driver", chromeDriverPath);
			  
			//Initiate Chrome driver instance.
			WebDriver driver = new ChromeDriver();
			*/ 
			
			//Must make the web browser full size other wise it can not parse out result by xpath.
			driver.manage().window().maximize();
			
			driver.get("http://www.yahoo.com");         
	        
			Thread.sleep(3000);      			
	        
			// Print out yahoo home page title.
			System.out.println("Page title is: " + driver.getTitle());	
			
			// Get yahoo search text box element.
			By searchBoxById = By.id("uh-search-box");
			WebElement searchBox = driver.findElement(searchBoxById);
			// Set search keyword.
			if(searchBox!=null)
			{
				searchBox.sendKeys("selenium");
				System.out.println("Input search keyword success.");
			}
			
			// Get yahoo search box submit element.
			By submitBtnById = By.id("uh-search-button");
			WebElement submitBtn = driver.findElement(submitBtnById);
			// Click submit button.
			if(submitBtn!=null)
			{
				submitBtn.click();
				System.out.println("Submit search form success.");
			}
			
			Thread.sleep(3000);
			
			// Get search result element list by xpath in search result page. 
			By resultListByXPath = By.xpath("//ol[@class=\"mb-15 reg searchCenterMiddle\"]/li");
			List resultElementList = driver.findElements(resultListByXPath);
			
			if(resultElementList!=null)
			{
				int size = resultElementList.size();
				System.out.println("Search result list size = " + size);
				// Loop the result list.
				for(int i=0;i<size;i++)
				{
					WebElement resultElement = resultElementList.get(i);
					
					try
					{
						// Get result item title element by xpath.
						By titleByXPath = By.xpath(".//a");
						WebElement titleELement = resultElement.findElement(titleByXPath);
						String title = "";
						if(titleELement!=null)
						{
							title = titleELement.getText();
						}
						
						if(!"".equals(title))
						{
							System.out.println("title = " + title);
						}
					}catch(NoSuchElementException ex)
					{
						ex.printStackTrace();
					}
					
					try
					{
						// Get result item description element by xpath.
						By descByXPath = By.xpath(".//div[@class=\"compText aAbs\"]");
						WebElement descElement = resultElement.findElement(descByXPath);
						String description = "";
						if(descElement!=null)
						{
							description = descElement.getText();
						}
						
						if(!"".equals(description))
						{
							System.out.println("description = " + description);
							System.out.println();
						}
					}catch(NoSuchElementException ex)
					{
						ex.printStackTrace();
					}
				}
			}
			
	        driver.quit();
		}catch(Exception ex)
		{
			ex.printStackTrace();
		}
	}
	
}

Above code output in Eclipse console.

READ :   Python Automation Scripts Examples Use Django And Selenium

phantomjs example parse yahoo search result output

Source Code

  1. Download “TestPhantomjsDriver.zip” TestPhantomjsDriver.zip – Downloaded 182 times – 1 KB

(Visited 3,621 times, 11 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.