如何在selenium中单击鼠标右键,然后在python中单击“将图像另存为”

如何在selenium中单击鼠标右键,然后在python中单击“将图像另存为”,python,selenium,web-crawler,Python,Selenium,Web Crawler,我试图用鼠标右键单击selenium python中的另存为图像。 我能够使用folling方法执行右键单击,但是执行右键单击的下一个操作不再有效。我怎样才能解决这个问题 from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys from selenium import webdriver driver.get(url) # get the image sou

我试图用鼠标右键单击selenium python中的另存为图像。 我能够使用folling方法执行右键单击,但是执行右键单击的下一个操作不再有效。我怎样才能解决这个问题

from selenium.webdriver import ActionChains 
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
driver.get(url)

    # get the image source
img = driver.find_element_by_xpath('//img')
actionChains = ActionChains(driver)
actionChains.context_click(img).send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.RETURN).perform()

您可以使用pyautogui执行相同的功能。假设您正在使用Windows。 -->pyautogui.position() (187567)#打印当前光标位置

-->pyautogui.moveTo(100200)#移动到需要右键单击的位置

-->pyautogui。单击(按钮='right')

-->pyautogui.热键('ctrl','c')-ctrl+c在键盘上(复制快捷键)

有关更多信息,请参阅下面的链接

您必须首先移动到要执行上下文单击的元素

从selenium.webdriver导入操作链
从selenium.webdriver.common.keys导入密钥
从selenium导入webdriver
获取驱动程序(url)
#获取图像源
img=driver。通过xpath(“//img”)查找元素
动作链=动作链(驱动程序)
actionChains.将\移动到\元素(img).上下文\单击().发送\键(键.箭头\向下).发送\键(键.箭头\向下).发送\键(键.返回).执行()

问题在于,send_keys()方法在创建上下文菜单后,会将键发送到窗口,而不是菜单。因此,无法访问菜单项

我在下载网页中创建的画布时遇到了类似的问题。最后,我能够下载执行javascript的图像。我创建了一个下载元素来管理图像。因为它是一个画布,所以我以前必须执行toDataURL方法。以下是我的python代码:

script_js = 'var dataURL = document.getElementsByClassName("_cx6")[0].toDataURL("image/png");' \
    'var link = document.createElement("a"); ' \
    'link.download = "{}_{}";' \
    'link.href = dataURL;' \
    'document.body.appendChild(link);' \
    'link.click();' \
    'document.body.removeChild(link);' \
    'delete link;'.format( n, prefijo_nombre_archivo, sufijo_nombre_archivo )
driver.execute_script(script_js)

我希望这会有帮助

是否要求您必须右键单击/另存为,或者您只是想通过任何必要的方式获取图像内容?@cody我需要右键单击/另存为,或者使用selenium浏览器下载图像时使用的会话和cookie,而不仅仅是简单的urlretrieve功能。这是一个很好的答案,但我需要将其应用于无头驱动程序。对不起,没有详细说明问题的细节。你能解释一下这个答案吗?看来这是唯一能帮我的。坦克。