duplicated text sent by actionchains send_keys when integrating in for loop python

Viewed 885

I try to send_keys to textarea so I use actionchains to send keys. I used this code:

url='https://translate.google.com/?hl=vi'
browserdriver.get(url)
list_test=['product description 1','product description 2']
for i in range (0,2):   
    try:
        body_text=list_test[i]
        browserdriver.execute_script("window.scrollTo(0, document.body.scrollHeight)")      
        item = WebDriverWait(browserdriver, 10).until(EC.presence_of_element_located((By.TAG_NAME, "textarea")))        
        actions.move_to_element(item).send_keys(body_text).perform()
        actions.reset_actions()
        time.sleep(1)
    except:
        pass
print("done")

And the result of text was sent to Google Translate as below:

product description 1product description 1product description 2

You can see that is so weird that it should be like this:

product description 1product description 2

I also inserted print() to utils.py in source code of actionchains in order to know what typing text is sent to send_keys function:

def keys_to_typing(value):
    """Processes the values that will be typed in the element."""
    typing = []
    for val in value:
        if isinstance(val, Keys):
            typing.append(val)
        elif isinstance(val, int):
            val = str(val)
            for i in range(len(val)):
                typing.append(val[i])
        else:
            for i in range(len(val)):
                typing.append(val[i])    
    print(typing)#this is a code line that I inserted
    return typing

and the output console of keys_to_typing is:

['p', 'r', 'o', 'd', 'u', 'c', 't', ' ', 'd', 'e', 's', 'c', 'r', 'i', 'p', 't', 'i', 'o', 'n', ' ', '1']
['p', 'r', 'o', 'd', 'u', 'c', 't', ' ', 'd', 'e', 's', 'c', 'r', 'i', 'p', 't', 'i', 'o', 'n', ' ', '1']

['p', 'r', 'o', 'd', 'u', 'c', 't', ' ', 'd', 'e', 's', 'c', 'r', 'i', 'p', 't', 'i', 'o', 'n', ' ', '2']
['p', 'r', 'o', 'd', 'u', 'c', 't', ' ', 'd', 'e', 's', 'c', 'r', 'i', 'p', 't', 'i', 'o', 'n', ' ', '2']

And this is the send_keys function in actionchains sourcecode:

def send_keys(self, keys_to_send):
        """
        Sends keys to current focused element.

        :Args:
         - keys_to_send: The keys to send.  Modifier keys constants can be found in the
           'Keys' class.
        """
        typing = keys_to_typing(keys_to_send)
        if self._driver.w3c:
            for key in typing:
                self.key_down(key)
                self.key_up(key)
        else:
            self._actions.append(lambda: self._driver.execute(
                Command.SEND_KEYS_TO_ACTIVE_ELEMENT, {'value': typing}))
        return self

Pls help me to explain this weird situation? I do not know why in loop for, actionchains.send_keys send duplicated content? thanks!

1 Answers

The problem is reset_actions() doesn't work as expected (adding perform() doesn't solve the problem). self.key_down(key) and self.key_up(key) in send_keys() stores the characters to type in self.w3c_actions.key_action

def key_down(self, value, element=None):
    if element:
        self.click(element)
    if self._driver.w3c:
        self.w3c_actions.key_action.key_down(value)
        self.w3c_actions.pointer_action.pause()
    else:
        self._actions.append(lambda: self._driver.execute(
            Command.SEND_KEYS_TO_ACTIVE_ELEMENT,
            {"value": keys_to_typing(value)}))
    return self

enter image description here

Those actions should be cleared when reset_actions() is called

def reset_actions(self):
    """
        Clears actions that are already stored locally and on the remote end
    """
    if self._driver.w3c:
        self.w3c_actions.clear_actions()
    self._actions = []

But they don't.

When send_keys() is called with product description 2 the text is added to key_action, which already contains the actions for typing product description 1 from the first for iteration, so it prints product description 1product description 2.

Possible solution is to create ActionChains instance inside the loop

for i in range(0, 2):
    try:
        body_text = list_test[i]
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
        item = WebDriverWait(driver, 10).until(ec.presence_of_element_located((By.TAG_NAME, "textarea")))
        actions = ActionChains(driver)
        actions.move_to_element(item).send_keys(body_text).perform()
        time.sleep(1)
    except:
        pass

Update

I opened an issue in bugs.chromium. The issue was reproduced, but won't be fixed (in the foreseeable future atleast).

Related