In this article, we are going to see how to drive headless chrome with Python. Headless Chrome is just a regular Chrome but without User Interface(UI). We need Chrome to be headless because UI entails CPU and RAM overheads.
For this, we will use ChromeDriver, Which is a web server that provides us with a way to interact with Headless Chrome. And Selenium, which is a framework that provides us with a set of functions to interact with ChromeDriver. So we can code desired actions that will be executed in the browser.
We write code using functions from Selenium. These functions are interacting with ChromeDriver. ChromeDriver tells Headless Chrome what to do.
Example 1: Basic example of automation of chrome
Here we are going to see how to automate chrome with selenium.
Function used:
- webdriver.Chrome(): Returns us an instance of Chrome driver through which we will be interacting with Chrome browser.
- driver.get(url): Send the browser a signal to get the specified URL.
- driver.close(): Send the browser a signal to close itself.
- time.sleep(n): Where n is an integer. Will suspend script execution on a specified amount of seconds. We need it to give us time to see that browser is running indeed.
Python3
import time from selenium import webdriver # initializing webdriver for Chrome driver = webdriver.Chrome() # getting GeekForGeeks webpage # sleep for 5 seconds just to see that # the browser was opened indeed time.sleep( 5 ) # closing browser driver.close() |
Example 2: Drive headless Chrome
Here we will automate the browser with headless, for we will use this function:
- webdriver.Chrome(): Returns us an instance of Chrome driver through which we will be interacting with Chrome browser.
- Options(): Through attributes of this class we can send browser launch parameters. In our case it is options.headless = True which will launch browser without UI(headless).
- driver.get(url): Send the browser a signal to get the specified URL.
- print(driver.title): Print webpage title into the terminal where we running our script.
- driver.close(): Send the browser a signal to close itself.
Python3
from selenium import webdriver from selenium.webdriver.chrome.options import Options # instance of Options class allows # us to configure Headless Chrome options = Options() # this parameter tells Chrome that # it should be run without UI (Headless) options.headless = True # initializing webdriver for Chrome with our options driver = webdriver.Chrome(options = options) # getting GeekForGeeks webpage # We can also get some information # about page in browser. # So let's output webpage title into # terminal to be sure that the browser # is actually running. print (driver.title) # close browser after our manipulations driver.close() |
Output:
As you can see we printed webpage title in the terminal.