首页 > 解决方案 > Selenium 无法在无头模式下工作

问题描述

所以我有一个基本的 Selenium 程序,你让它点击一个按钮,你应该得到一个“Hello World”文本复制到你的剪贴板。如果代码不在无头模式下,该代码可以工作,但我希望它在无头模式下工作。这是启用无头模式的代码:

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)

这是HTML代码:

<!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>

标签: python-3.xselenium-chromedriver

解决方案


我遇到了同样的问题,并且在无头模式下呈现的页面似乎有所不同。显式设置窗口大小为我修复了它。

您可以在选项中设置它:

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

或直接在代码中:

driver.set_window_size(1440, 900)

推荐阅读