简体   繁体   English

如何使用 Selenium 和 Python 将图像从浏览器本机菜单复制到剪贴板

[英]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'.这相当于在 web 上查看图像,右键单击它,然后单击“复制图像”。 I'm attempting to automate this using selenium, what's the most efficient way to do this?我正在尝试使用 selenium 自动执行此操作,最有效的方法是什么?

First, you can use one of the many options Selenium offers for finding an element.首先,您可以使用 Selenium 提供的众多选项之一来查找元素。 In your case, you're probably looking for a img HTML tag, or something similar.在您的情况下,您可能正在寻找img HTML 标签或类似标签。

After you've gotten the element, you can run the .get_attribute("src") method to get the source URL for the picture.获取元素后,可以运行.get_attribute("src")方法获取图片的源 URL。 You can then pair this with a module like requests to download the picture to your computer: (Taken from this answer)然后,您可以将其与requests将图片下载到您的计算机之类的模块配对:(取自答案)

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 -> Copy image执行的。


context_click()上下文点击()

context_click() is generally invoked on a WebElement eg a link . context_click()通常在WebElement上调用,例如链接

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.在元素上调用context_click()会打开一个浏览器原生上下文菜单,该菜单是浏览器原生操作,设计上不能由 Selenium 管理。


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.使用Selenium您将无法使用send_keys(Keys.ARROW_DOWN)send_keys(Keys.DOWN)等与浏览器原生上下文菜单项进行交互。


Reference参考

You can find a relevant discussion in:您可以在以下位置找到相关讨论:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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