简体   繁体   English

Python 3 硒 | 剪贴板不适用于 Windows 上的无头 chromedriver

[英]Python 3 Selenium | Clipboard not working on headless chromedriver on Windows

In StackOverflow, there is already a similar post about this topic.在 StackOverflow 中,已经有一篇关于此主题的类似帖子 Though the OP of the post answered stating that " this is a bug in Windows " and that " I did not find a solution, I just cut part of my code out ".尽管帖子的 OP 回答说“这是 Windows 中的一个错误”并且“我没有找到解决方案,我只是删掉了部分代码”。

I have a slightly different circumstance.我的情况略有不同。 I cannot cut the part of the code out but I can use different web browsers.我无法删除部分代码,但我可以使用不同的网络浏览器。

My Circumstance:我的情况:

I need to write a specific text into a text box.我需要将特定文本写入文本框。 Unfortunately, the text I am writing includes few instances of emojis , thus send_keys() was not an option.不幸的是,我正在写的文本包含很少的emojis实例,因此send_keys()不是一个选项。 Instead, with the help of StackOverflow, I end up using pyperclip.copy(text) and element.send_keys(Keys.CONTROL,'v') which works fine (it successfully copied the emojis).相反,在 StackOverflow 的帮助下,我最终使用pyperclip.copy(text)element.send_keys(Keys.CONTROL,'v')效果很好(它成功复制了表情符号)。

But I also need the ChromeDriver to be --headless .但我还需要 ChromeDriver 为--headless Everything worked well, except for the copy-paste part.除了复制粘贴部分外,一切都运行良好。

My question我的问题

My question is: how should I tackle this issue?我的问题是:我应该如何解决这个问题?

  • Web browser must be hidden (ex. --headless at ChromeDriver)必须隐藏 Web 浏览器(例如--headless at ChromeDriver)
  • it can write emojis into a text element它可以将表情符号写入文本元素
  • has to work on Windows OS (Windows 7 - 10)必须在 Windows 操作系统 (Windows 7 - 10) 上工作

I had the same issue so I used klembord instead of pyperclip.我遇到了同样的问题,所以我使用 klembord 而不是 pyperclip。

https://pypi.org/project/klembord/ https://pypi.org/project/klembord/

# pip install webdriver-manager
# pip install klembord
# pip install selenium
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from webdriver_manager.firefox import GeckoDriverManager
import klembord
klembord.init()
options = Options()
options.headless = True
driver = webdriver.Firefox(options=options,executable_path=GeckoDriverManager().install())
print("Headless Firefox Initialized. Wait for output")
driver.get("https://www.lipsum.com")
l = driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/div[3]/div[1]/p")
klembord.set_text(l.text) # setting text to clipboard
print("Check clipboard by pressing WIN + V or CTRL +V")
driver.quit()

From what I can find, it seems there is no way to access the clipboard in headless mode.据我所知,似乎无法以无头模式访问剪贴板。 I can't find anything definitive but this is as close as I can get to proof that it can't be done: https://groups.google.com/g/selenium-users/c/-nxTX4eTbwA/m/wQY_HlZQBAAJ我找不到任何确定的东西,但这是我能证明它无法完成的最接近的证据: https ://groups.google.com/g/selenium-users/c/-nxTX4eTbwA/m/wQY_HlZQBAAJ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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