2

I'm trying to automate the task of taking an image or source element, and copying it to my clipboard. This is the equivalent to seeing an image on the web, right clicking it, and clicking 'copy image'. I'm attempting to automate this using selenium, what's the most efficient way to do this?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
paull
  • 15
  • 2
  • 7

2 Answers2

0

First, you can use one of the many options Selenium offers for finding an element. In your case, you're probably looking for a img HTML tag, or something similar.

After you've gotten the element, you can run the .get_attribute("src") method to get the source URL for the picture. You can then pair this with a module like requests to download the picture to your computer: (Taken from this answer)

import requests
...
r = requests.get(element.get_attribute("src"), stream = True)
if r.status_code == 200:
    with open(filePath, 'wb') as f:
        for chunk in r:
            f.write(chunk)

Finally, you can use a module like the one used in this answer to copy the downloaded image to your clipboard.

Xiddoc
  • 3,369
  • 3
  • 11
  • 37
  • thanks for answering. I know there is src attribute but what if you want just to copy to the clipboard ...and the link you provided I checked before asking the question .. but they didn't explain how to get from the web ... thanks ... – paull Jun 18 '20 at 07:49
  • Yes, and like my answer says, you can then locate it using the built-in methods, download it, and copy it to your clipboard. Also, remember to flag the correct answer accordingly once you've gotten it. – Xiddoc Jun 18 '20 at 07:50
  • I edited my post to include the requests part of the code. – Xiddoc Jun 18 '20 at 07:59
  • I think this will solve my question but my case is that I want just to copy the image to clipboard not to download it – paull Jun 18 '20 at 08:08
  • I'm not sure if there's a built-in for directly copying the file without downloading it, but after you've downloaded it you can copy the data from the picture. If you don't want the picture afterwards, you can always use `os.remove(file)` to delete it. – Xiddoc Jun 18 '20 at 08:10
  • That's what I want . copy the image directly without downloading it ... – paull Jun 18 '20 at 08:21
0

Essentially, copying an image to the clipboard is performed through Context Click -> Copy image.


context_click()

context_click() is generally invoked on a WebElement e.g. a link.

Invoking context_click() on a element opens a browser native context menu which is a browser native operation and can't be managed by Selenium by design.


Conclusion

Using Selenium you won't be able to interact with browser native context menu items using send_keys(Keys.ARROW_DOWN), send_keys(Keys.DOWN), etc.


Reference

You can find a relevant discussion in:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352