Python And Selenium - Avoid Submit Form When Send_keys() With Newline
I am using Python 3 with selenium. Let's assume var = 'whatever\nelse' My problem is that when I use elem.send_keys(var) it sends the form after 'whatever' (because of the newline)
Solution 1:
Did you tried something like:
ActionChains(driver).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.ENTER).perform()
Like
from selenium import webdriver
from selenium.webdriver.common.keysimportKeysfrom selenium.webdriver.common.action_chainsimportActionChains
driver = webdriver.Chrome()
driver.get('http://foo.bar')
inputtext = 'foo\nbar'
elem = driver.find_element_by_tag_name('div')
for part in inputtext.split('\n'):
elem.send_keys(part)
ActionChains(driver).key_down(Keys.SHIFT).key_down(Keys.ENTER).key_up(Keys.SHIFT).key_up(Keys.ENTER).perform()
ActionChains
will chain key_down
of SHIFT + ENTER + key_up
after being pressed.
Like this you perform your SHIFT
+ ENTER
, then release buttons so you didn't write all in capslock (because of SHIFT)
PS: this example add too many new lines (because of the simple loop on inputtext.split('\n')
, but you got the idea.
Solution 2:
This is the method I actively use. At least this is simpler.
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://foo.bar')
text = "any\ntext"
textarea = webdriver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div[2]/div/div[2]') #find elementif'\r\n'in text: #check if exists \n tag in text
textsplit = text.split("\r\n") #explode
textsplit_len = len(textsplit)-1#get last elementfor text in textsplit:
textarea.send_keys(text)
if textsplit.index(text) != textsplit_len: #do what you need each time, if not the last element
textarea.send_keys(Keys.SHIFT+Keys.ENTER)
Post a Comment for "Python And Selenium - Avoid Submit Form When Send_keys() With Newline"