简体   繁体   中英

How to Copy image to clipboard from the browser native menu using Selenium and Python

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?

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.

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


context_click()

context_click() is generally invoked on a WebElement eg 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:

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