简体   繁体   中英

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>

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM