PhantomJS Example

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

1. Preparation For Using PhantomJS.

  1. Add selenium-server-standalone-3.5.3.jar in Eclipse java project build path. You can read the article How To Add Selenium Server Standalone Jar File Into Eclipse Java Project And Maven Project to learn how to do it.
  2. Click download PhantomJS to go to PhantomJS browser executable file download page to get the related version.
  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.
  5. Add phantomjsdriver-1.1.0.jar in Eclipse java project build path also, you can refer to step 1.

2. PhantomJS Driver Example Java Code.

  1. This example code will use PhantomJS driver to open PhantomJS headless browser.
  2. It will browse yahoo.com, input search keywords in the search text box, and parse out the search result list data on the result page.
  3. Please Note: After you create the PhantomJS driver, you must maximize it, otherwise it will not return web elements when you use the 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();
    		}
    	}
    	
    }
  4. Below is the above code output in the Eclipse console.
    Page title is: Yahoo
    Input search keyword success.
    Submit search form success.
    Search result list size = 11
    
    title = Selenium: Benefits, Uses, Side Effects, Dosage, and More
    description = Selenium has antioxidant properties and may help protect cells from damage. Most people get enough of ti
    title = Selenium - Web Browser Automation
    description = Selenium WebDriver If you want to create robust, browser-based regression automation suites and tests; 5
    
    title = Selenium - Dietary Supplement Fact Sheet
    description = Selenium is a trace element that is naturally present in many foods, added to others, and available as E
    
    title = Selenium - Wikipedia
    description = Selenium is a chemical element with symbol Se and atomic number 34. It is a nonmetal with properties the
    
    title = Selenium | University of Maryland Medical Center
    description = Overview. Selenium is an essential mineral found in small amounts in the body. It works as an antioxidar
    
    title = Selenium WebDriver
    description = Selenium WebDriver. The biggest change in Selenium recently has been the inclusion of the HebDriver API.
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Matrix Archtect
Matrix Archtect

very good

1
0
Would love your thoughts, please comment.x
()
x