python-3.x - 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>
解决方案
我遇到了同样的问题,并且在无头模式下呈现的页面似乎有所不同。显式设置窗口大小为我修复了它。
您可以在选项中设置它:
chrome_options.add_argument("--window-size=1440, 900")
或直接在代码中:
driver.set_window_size(1440, 900)
推荐阅读
- php - 选择下拉菜单始终显示最后一个选择
- azure - 如何为相同资源类型的多个资源创建不同的指标类型警报
- python - 如何解析 Airflow 中的嵌套宏
- c# - 如何使用 c# 运行 exe 文件(我不能使用 Process.Start() 因为我不知道 exe 文件的位置)
- java - JSF @Inject 机制返回 NullPointerException
- python-3.x - 如何让 Python 什么都不做
- python - 无需训练模型的人指甲分割
- css - 无法让我的动态 CSS 与 Vue.js 一起使用
- sql - 来自相同输出的对象总和
- java - 在单击侦听器回调中获取活动上下文