Send a random text containing an emoji from a list using send_keys in Selenium

Question:

I’m trying to send a message using send_keys() by picking a random item containing an emoji from a list:

gm = [
  'Good morning  ',
  'Good morning ☀️',
  'Good morning ⛅',
  'Good morning  ',
  'Good morning  ',
  'Good morning  ',
  'Good morning ⛅',
  'Good morning  ️',
  'Good morning  ️',
  'Good morning ☕',
]

Sending the text directly containing an emoji works fine like so:

textbox = driver.find_element(By.XPATH, textbox_xpath)
textbox.send_keys('Good morning ☀️' + Keys().ENTER)

But having it pick a random value from the list as the text input does not work and results in the error: selenium.common.exceptions.WebDriverException: Message: unknown error: ChromeDriver only supports characters in the BMP.

textbox = driver.find_element(By.XPATH, textbox_xpath)
textbox.send_keys(random.choice(gm) + Keys().ENTER)

Any help would be appreciated.

Asked By: Tony

||

Answers:

try encoding it first before passing it over to sendkeys()

textbox = driver.find_element(By.XPATH, textbox_xpath)
encoded = (random.choice(gm)).encode("utf-8")
textbox.send_keys(encoded  + Keys().ENTER)

Something like that, just a heads up that I’ve not tried it yet. do try it out.

Since utf-8 is already in unicode, and if it still doesn’t work, you may need to change drivers as suggested by a user here. either gecko or firefox drivers. I believe this only affects sendkeys() function. so if you have any other alternative methods to get the job done, you should consider them as well

https://stackoverflow.com/a/59139690/12128167

Answered By: Sin Han Jinn

Turns out, I was never able to directly send most of the emojis besides this one: ☀️, because of some Unicode issues. Encoding with ('utf-8') also did not work. Instead, I created a workaround to simply use the Clipboard by copying a random emoji directly from https://emojipedia.org/ in a new tab and then sending a Ctrl-v command through sendKeys().

EMOJI_XPATH = '/html/body/div[5]/div[1]/article/section[1]/form/label/button'
emoji_list = [
    'https://emojipedia.org/sun/',
    'https://emojipedia.org/sun-with-face/',
    'https://emojipedia.org/sunrise/',
]

driver.get(random.choice(emoji_list))
emoji = driver.find_element(By.XPATH, EMOJI_XPATH)
emoji.click()  # clicks 'Copy' button

# runs JS code to open a new tab
driver.execute_script("window.open('about:blank', 'secondtab');")
driver.switch_to.window('secondtab')
driver.get('https://yourURL.com')
textbox = driver.find_element(By.XPATH, TEXTBOX_XPATH)
textbox.send_keys('Good morning ' + Keys().CONTROL, 'v')
textbox.send_keys(Keys().ENTER)
Answered By: Tony