简体   繁体   中英

How to paste text from clipboard on mac while running selenium - Python

I have a function that verifies the data copied to clipboard

def verify_copied_transcript_data(self):
    selector = '//input[@type="text" and @name="topic"]'
    topic_field = self.wait_for_element_by_xpath(selector)
    topic_field.clear()
    topic_field.send_keys('')
    topic_field.send_keys(Keys.COMMAND, 'v')
    topic_field_value = topic_field.get_attribute('value')
    self.assertTrue(len(topic_field_value) > 0)

I have verified that manually CMD + v does paste the copied text on the topic_field. Any idea why selenium would not simulate topic_field.send_keys(Keys.COMMAND, 'v')

The function to copy the text is:

def click_copy_transcript(self):
    selector = '//div[@id="closeChatModal"]//span[contains(text(), "Copy All")]'
    self.wait_for_element_by_xpath(selector).click()

This copies the text on clipboard

Try this:

topic_field.send_keys(Keys.COMMAND + 'v')

The full code would be:

def verify_copied_transcript_data(self):
    selector = '//input[@type="text" and @name="topic"]'
    topic_field = self.wait_for_element_by_xpath(selector)
    topic_field.clear()
    topic_field.send_keys('')
    topic_field.send_keys(Keys.COMMAND + 'v')
    topic_field_value = topic_field.get_attribute('value')
    self.assertTrue(len(topic_field_value) > 0)

Also you can try to use ActionChains:

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

ActionChains(driver) \
    .key_down(Keys.COMMAND) \
    .key_down('v') \
    .key_up('v') \
    .key_up(Keys.COMMAND) \
    .perform()

How about this:

ActionChains(driver).key_down(u'\').key_down('v').perform()

or even:

ActionChains(driver).key_down(u'\').send_keys('v').perform()

I've checked it on a PC using the Control key instead of Command (obviously!) and both work.

PS. Perhaps first you might need to simulate a click into the field you want to paste the buffer.

As you mentioned the following code copies the text to the clipboard :

def click_copy_transcript(self):
    selector = '//div[@id="closeChatModal"]//span[contains(text(), "Copy All")]'
    self.wait_for_element_by_xpath(selector).click()

Now, to copy the text from the clipboard you can use the paste() method from Pyperclip – A cross-platform clipboard module for Python as follows:

import pyperclip

def click_copy_transcript(self):
    selector = '//div[@id="closeChatModal"]//span[contains(text(), "Copy All")]'
    self.wait_for_element_by_xpath(selector).click()
    topic_field.send_keys(pyperclip.paste())

Note : As per adam-p/cb.py it is mentioned as:

Python function to copy text to clipboard (so far only supports Windows).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM