Home > database >  selenium send_keys formatting
selenium send_keys formatting

Time:06-03

I want to fill a text to a selected element which is a chatbox like this:

Hi,
It's me

I tried to write the code like this:

element.send_keys("""
Hi,
It's me
"""")

The thing is "Hi" is sent unintentionally to the chat and leaves "It's me" in the chatbox. Is there an alternative?

CodePudding user response:

The simpliest way how to do this is by adding an "Enter" key in the middle of the string.

import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--start-maximized")
chromedriver = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'chromedriver.exe')
chrome = webdriver.Chrome(chromedriver, options=chrome_options)

chrome.get("https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_textarea")

iframe = chrome.find_element_by_xpath('//*[@id="iframeResult"]')
chrome.switch_to.frame(iframe)
chrome.find_element_by_xpath('//*[@id="w3review"]').clear()
chrome.find_element_by_xpath('//*[@id="w3review"]').send_keys("Hello"   Keys.ENTER   "World")

However, this will most likely not work in your "chat app". The reason being is that "Enter" is also used to send the message. If that is the case, you need to use an action chain. Here is an example how it can be done:

from selenium.webdriver.common.action_chains import ActionChains

action = ActionChains(chrome)

el = chrome.find_element_by_xpath('//*[@id="w3review"]')

action.move_to_element(el)\
    .click(el)\
    .send_keys("Hello")\
    .key_down(Keys.SHIFT)\
    .send_keys(Keys.ENTER)\
    .key_up(Keys.SHIFT)\
    .send_keys("World")\
    .perform()
  • Related