selenium send_keys formatting



我想填充一个文本到一个选定的元素,它是一个聊天框,像这样:

Hi,
It's me

我试着这样写代码:

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

事情是"Hi"无意中被发送到聊天室,然后离开了"是我"。在聊天箱里。有别的选择吗?

最简单的方法是添加"Enter">

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

然而,这很可能在你的"聊天应用"中不起作用。原因是"进入";也用于发送消息。如果是这种情况,您需要使用动作链。下面是一个如何做到这一点的例子:

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

相关内容

最新更新