Home > Software design >  How can I adapt the following code to run in headless mode?
How can I adapt the following code to run in headless mode?

Time:04-23

I am working with the following code:

import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver

PATH= r"C:\Users\Hamid\Desktop\Selenium\chromedriver.exe"

driver=webdriver.Chrome(PATH)
driver.get("https://www.google.com/")
click_button=driver.find_element_by_xpath('//*[@id="L2AGLb"]/div').click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.NAME, "q"))).send_keys("ONS data")
search=driver.find_element_by_xpath('/html/body/div[1]/div[3]/form/div[1]/div[1]/div[3]/center/input[1]').click()

How can I adapt it so that it runs on headless mode?

CodePudding user response:

Seems you are using Selenium v3.x. So to use the headless mode you just have to set the --headless property to true through an instance of Options() class as follows:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

options = Options()
options.headless = True
PATH= r"C:\Users\Hamid\Desktop\Selenium\chromedriver.exe"
driver=webdriver.Chrome(executable_path=PATH, options=options)
driver.get("https://www.google.com/")
click_button=driver.find_element_by_xpath('//*[@id="L2AGLb"]/div').click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.NAME, "q"))).send_keys("ONS data")
  • Related