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
driver = webdriver.Chrome()
time.sleep( 5 )
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
options = Options()
options.headless = True
driver = webdriver.Chrome(options = options)
print (driver.title)
driver.close()
|
Output:
As you can see we printed webpage title in the terminal.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
19 Dec, 2021
Like Article
Save Article