Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium not working in headless mode

So I have a basic Selenium program, where you make it click on a button and you should get a "Hello World" text copied to your clipboard. The code works if it's not in headless mode, but I want it to work in headless mode. Here's the code with headless mode enabled:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import pyperclip

CHROME_PATH = 'C:\\Program Files 
(x86)\\Google\\Chrome\\Application\\chrome.exe'
CHROMEDRIVER_PATH = 'C:\\Users\\ACER\\Desktop\\chromedriver_win32\\chromedriver.exe'
chrome_options = Options()
chrome_options.set_headless()
driver = webdriver.Chrome(executable_path=CHROMEDRIVER_PATH,
                          chrome_options=chrome_options
                         )  

driver.get("file://C:/Users/ACER/Desktop/index.html")
driver.find_element_by_class_name("button").click()

message = pyperclip.paste()

driver.close()

if message == "":
    print("Failed")
else:
    print(message)

Here is the HTML code:

<!DOCTYPE html>
<html>
<head>
<style>
  .wrapper {
   text-align: center;
}

  .button {
   background-color: black;
   border: none;
   color: white;
   padding: 20px 30px;
   font-size:30px;
   cursor: pointer;
}

  .button:hover {
   background-color: grey;
}
</style>
</head>
<body>

<div class="wrapper">
    <button class="button" onclick="copyToClipboard('Hello World')">Click 
Here</button>
</div>

<script type="text/javascript">
  function copyToClipboard(text){
       var dummy = document.createElement("input");
       document.body.appendChild(dummy);
       dummy.setAttribute('value', text);
       dummy.select();
       document.execCommand("copy");
       document.body.removeChild(dummy);
}
</script>
</body>
</html>
like image 891
MrSpunkey Avatar asked Oct 21 '25 04:10

MrSpunkey


1 Answers

I had the same problem and it appeared the page rendered differently in headless mode. Explicitly setting the window size fixed it for me.

You can either set it in the options:

chrome_options.add_argument("--window-size=1440, 900")

or directly in code:

driver.set_window_size(1440, 900)
like image 59
spannerj Avatar answered Oct 26 '25 18:10

spannerj