Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

How may I replace "whatever\nelse" with whatever + SHIFT+ENTER + else?

Or is there any other way to input newlines without actually using javascript or substituting newlines with the newline keystroke?

Note: elem is a contenteditable div.

like image 426
Álvaro N. Franz Avatar asked Jul 21 '17 11:07

Álvaro N. Franz


People also ask

How do you break a line in selenium?

A line feed is "\n" or "\u000a" , and a carriage return is "\r" is "\u000d" .

How do I add a new line in selenium?

Selenium WebDriver - How to type text in a new line inside a text area ? Use \n for new line.

How do you press Enter in Python using selenium?

We can type Enter/Return key in Selenium. We shall use the sendKeys method and pass Keys. ENTER as an argument to the method. Also, we can use pass Keys.

Can we automate web application using Python?

You have learned that Python can do everything that a web browser can do, and a bit more. You could easily write scripts to control virtual browser instances that run in the cloud. You could create bots that interact with real users or mindlessly fill out forms! Go forth and automate!


1 Answers

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.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

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.

like image 123
Arount Avatar answered Sep 24 '22 08:09

Arount