Performing a copy and paste with Selenium 2

后端 未结 8 1845
广开言路
广开言路 2020-11-30 05:05

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

相关标签:
8条回答
  • 2020-11-30 05:34

    I cannot try this on OSX at the moment, but it definitely works on FF and Ubuntu:

    import os
    import time
    
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    
    with open('test.html', 'w') as fp:
        fp.write("""\
    <html>
    <body>
      <form>
        <input type="text" name="intext" value="ABC">
        <br>
        <input type="text" name="outtext">
      </form>
    </body>
    </html>
    """)
    
    driver = webdriver.Firefox()
    driver.get('file:///{}/test.html'.format(os.getcwd()))
    element1 = driver.find_element_by_name('intext')
    element2 = driver.find_element_by_name('outtext')
    time.sleep(1)
    element1.send_keys(Keys.CONTROL, 'a')
    time.sleep(1)
    element1.send_keys(Keys.CONTROL, 'c')
    time.sleep(1)
    element2.send_keys(Keys.CONTROL, 'v')
    

    The sleep() statements are just there to be able to see the steps, they are of course not necessary for the program to function.

    The ActionChain send_key just switches to the selected element and does a send_keys on it.

    0 讨论(0)
  • 2020-11-30 05:36

    Solution for both Linux and MacOS (for Chrome driver, not tested on FF)

    The answer from @BradParks almost worked for me for MacOS, except for the copy/cut part. So, after some research I came up with a solution that works on both Linux and MacOS (code is in ruby). It's a bit dirty, as it uses the same input to pre-paste the text, which can have some side-effects. If it was a problem for me, I'd try using different input, possibly creating one with execute_script.

      def paste_into_input(input_selector, value)
        input = find(input_selector)
        # set input value skipping onChange callbacks
        execute_script('arguments[0].focus(); arguments[0].value = arguments[1]', input, value)
        value.size.times do
          # select the text using shift + left arrow
          input.send_keys [:shift, :left]
        end
        execute_script('document.execCommand("copy")') # copy on mac
        input.send_keys [:control, 'c'] # copy on linux
    
        input.send_keys [:shift, :insert] # paste on mac and linux
      end
    
    0 讨论(0)
提交回复
热议问题