Python 3 Selenium | Clipboard not working on headless chromedriver on Windows

Viewed 2481

In StackOverflow, there is already a similar post about this topic. 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".

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. 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).

But I also need the ChromeDriver to be --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)
  • it can write emojis into a text element
  • has to work on Windows OS (Windows 7 - 10)
1 Answers

I had the same issue so I used klembord instead of pyperclip.

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()
Related