Home > Software design >  How do you use headless Chrome with Selenium?
How do you use headless Chrome with Selenium?

Time:12-21

This question is asked because I want to know what is the optimal way to do this in 2021 as there have been changes and I see that people are doing it differently.

I want to be able to automate my Twitter follow bot in the background, using headless. I am also new to Python and still learning so I'd appreciate code lines.

Code:

import tkinter as tk

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from selenium.webdriver.chrome.options import Options

from selenium.webdriver.chrome.service import Service

options = webdriver.ChromeOptions()
options.add_argument("--headless")
options.add_argument("start-maximized")

ser = Service("C:\Program Files (x86)\chromedriver.exe")

import time

from time import sleep

root = tk.Tk()

app_width = 300
app_height = 320

screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

x = (screen_width / 2) - (app_width / 2)
y = (screen_height / 2) - (app_height / 2)

root.geometry(f'{app_width}x{app_height} {int(x)} {int(y)}')

testbtn_txt = tk.StringVar()
testbtn = tk.Button(root, textvariable=testbtn_txt, command=lambda:open_browser_func(), font="Arial", bg="#808080", fg="white", height=1, width=10)
testbtn_txt.set("Test")
testbtn.grid(row=10, column=0, columnspan=2, pady=5, padx=5)


def open_browser_func():
    global driver
    
    driver = webdriver.Chrome(service=ser, options=options)

    driver.get("https://twitter.com/i/flow/login")
    sleep(5)

    wait = WebDriverWait(driver, 30)
    loginuser  = wait.until(EC.visibility_of_element_located((By.NAME, "text")))
    loginuser.send_keys("User", Keys.RETURN)
    loginPassword = wait.until(EC.visibility_of_element_located((By.NAME, "password")))
    loginPassword.send_keys("Pass", Keys.RETURN)
    
    sleep(10)
    driver.get_screenshot_as_file("logged_in_shot.png")
    return driver

root.mainloop()

CodePudding user response:

Generally, your code is almost correct.
However instead of

options.add_argument("start-maximized")

AFAIK it should be

options.add_argument("--start-maximized")

Also I think it's preferred to set the window size explicitly, something like

options.add_argument("--window-size=1920,1080")

instead of

options.add_argument("--start-maximized")
  • Related