Python selenium send_keys 表情符号支持

标签 python selenium

我正在尝试使用 selenium 的 send_keys 将表情符号字符发送到具有以下 python 代码的文本框。

browser = webdriver.Chrome(chrome_options=options)
browser.get("https://www.google.co.in")
time.sleep(5)
working = browser.find_element_by_id('lst-ib')
text = u'Python is 👍'
working.send_keys(text)

我收到以下错误。

Traceback (most recent call last):
  File "smiley.py", line 30, in <module>
    working.send_keys(text)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 347, in send_keys
    self._execute(Command.SEND_KEYS_TO_ELEMENT, {'value': keys_to_typing(value)})
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", line 491, in _execute
    return self._parent.execute(command, params)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 238, in execute
    self.error_handler.check_response(response)
  File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 164, in check_response
    raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message: missing command parameters

经过搜索,我发现 selenium send_keys 只支持单字节字符。但我想知道,是否有任何替代方法可以实现这一目标。

我已经尝试使用 CTRl + C 和 CTRL + V 组合,它正在工作。但有时剪贴板内容在粘贴之前会发生变化(复制和粘贴几乎立即发生)。

我也无法使用 execute_script 设置字段的值,因为它不是输入元素而是跨度。我可以设置 inner_text 但在我的用例中没用。

更新: 我使用了一些解决方法来解决剪贴板覆盖问题。下面提供了工作代码。

schedule = urllib2.urlopen(request,context=ctx)
text = schedule.read().decode('utf-8')
elem = browser.find_element_by_class_name(xpathObj['commentLink'])
elem.click()
time.sleep(2)
ActionChains(browser).send_keys('a').perform()
time.sleep(2)
copy_attempt = 0
while True:
    span_element = browser.find_element_by_xpath(xpathObj['commentSpan'])
    browser.execute_script("arguments[0].innerText = arguments[1]", span_element, text)
    time.sleep(2)
    ActionChains(browser).key_down(Keys.CONTROL).send_keys('a').key_up(Keys.CONTROL).perform()
    time.sleep(1)
    ActionChains(browser).key_down(Keys.CONTROL).send_keys('c').key_up(Keys.CONTROL).key_down(Keys.CONTROL).send_keys('V').key_up(Keys.CONTROL).perform()
    time.sleep(1)
    win32clipboard.OpenClipboard()
    text1 = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
    emoji_pattern = re.compile(
        u"(\ud83d[\ude00-\ude4f])|"  # emoticons
        u"(\ud83c[\udf00-\uffff])|"  # symbols & pictographs (1 of 2)
        u"(\ud83d[\u0000-\uddff])|"  # symbols & pictographs (2 of 2)
        u"(\ud83d[\ude80-\udeff])|"  # transport & map symbols
        u"(\ud83c[\udde0-\uddff])"   # flags (iOS)
        "+", flags=re.UNICODE)
    s = difflib.SequenceMatcher(None,emoji_pattern.sub(r'', text), emoji_pattern.sub(r'', text1))
    if (s.ratio() < 1.0):
        if (copy_attempt < 5):
            copy_attempt = copy_attempt + 1
            continue
        else:
            break
    else:
        ActionChains(browser).send_keys(Keys.RETURN).perform()
        time.sleep(3)
        break
time.sleep(3)

谢谢大家

最佳答案

使用当前版本的 chrome 驱动程序 (2.32),send_keys 方法仅支持来自 Basic Multilingual Plane 的字符.

如果您想输入表情符号,则必须使用脚本注入(inject)通过 value 属性将文本写入所需的输入。您还必须发送 change 事件来通知监听器:

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.google.co.in")

time.sleep(5)

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

elem = driver.find_element_by_id('lst-ib')
text = u'\ud83d\udc4d'

driver.execute_script(JS_ADD_TEXT_TO_INPUT, elem, text)

关于Python selenium send_keys 表情符号支持,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45330640/

相关文章:

python - python 中超过限制时如何更改 api token ?

python - 测试python中是否存在互联网连接

python selenium headless chromedriver在前一天工作时没有加载整页,代码没有改变

java - 让 WebDriver 在没有 ExpectedCondition 的情况下等待

java - 在 Selenium WebDriver 中保存包含所有 Assets 的整个网页

Python Selenium 错误处理

python - 在 tkinter Toplevel 中调整 matplotlib 图的大小

python - 是否有可能 "hint"字典键?

python - 如何将项目列表转换为python中的变量?

python - selenium.common.exceptions.ElementNotVisibleException : Message: Element is not currently visible and so may not be interacted with