Search code examples
pythonseleniumselenium-webdriverautomationselenium-chromedriver

Sending emojis with Selenium Python


I know that questions like this have already been asked but I have not found a clear answer that really works.

I want to send automatically dm on social medias but I want to add emojis in it. The thing is that I don't understand how do people send it because it is not allowed by the Chromedriver (it is said that only BMP is supported).

Indeed, I have found a solution to add text in an input, which is as follows :

JS_ADD_TEXT_TO_INPUT = """
var elm = arguments[0], txt = arguments[1];
elm.value += txt;
elm.dispatchEvent(new Event('change'));
"""

In my case, the place where i want to add emoji is not always an input (it can be a span or a div). Does someone have an idea about what code could help me to do that ? Thanks in advance !


Solution

  • If you're trying to add an emoji to a non-input field, you could set the textContent directly to it.

    script = """document.querySelector('%s').textContent='%s';""" % (
            css_selector,
            value,
        )
    driver.execute_script(script)
    

    Be sure to escape any quotes & special characters before feeding a selector in there. Eg. import re; re.escape(css_selector)

    That will let you set any text on a web page element to anything, including emojis if you're not typing into an input field.