Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 views
in Technique[技术] by (71.8m points)

Performing a copy and paste with Selenium 2

Is there any way to perform a copy and paste using Selenium 2 and the Python bindings?

I've highlighted the element I want to copy and then I perform the following actions

copyActionChain.key_down(Keys.COMMAND).send_keys('C').key_up(Keys.COMMAND)

However, the highlighted text isn't copied.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To do this on a Mac and on PC, you can use these alternate keyboard shortcuts for cut, copy and paste. Note that some of them aren't available on a physical Mac keyboard, but work because of legacy keyboard shortcuts.

Alternate keyboard shortcuts for cut, copy and paste on a Mac

  • Cut => control+delete, or control+K
  • Copy => control+insert
  • Paste => shift+insert, or control+Y

If this doesn't work, use Keys.META instead, which is the official key that replaces the command ? key

source: https://w3c.github.io/uievents/#keyboardevent

Here is a fully functional example:

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

browser = webdriver.Safari(executable_path = '/usr/bin/safaridriver')
browser.get("http://www.python.org")
elem = browser.find_element_by_name("q")
elem.clear()
actions = ActionChains(browser)
actions.move_to_element(elem)
actions.click(elem) #select the element where to paste text
actions.key_down(Keys.META)
actions.send_keys('v')
actions.key_up(Keys.META)
actions.perform() 

So in Selenium (Ruby), this would be roughly something like this to select the text in an element, and then copy it to the clipboard.

# double click the element to select all it's text
element.double_click 

# copy the selected text to the clipboard using CTRL+INSERT
element.send_keys(:control, :insert)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...