如何在Python中使用Selenium进行右键单击并保存图像

5

我正在尝试使用Selenium Python右键单击鼠标并单击“另存为图像”。我已经使用以下方法执行了右键单击,但是下一步要执行的右键单击操作不再起作用。我该如何解决这个问题?

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()

您必须右键单击/另存为吗?还是您只是想通过任何可用的方式获取图像内容? - cody
@cody,我需要右键点击/另存为或者使用与Selenium浏览器下载图像时相同的会话和cookie,而不仅仅是简单的urlretrieve函数。 - 강희명
3个回答

4
问题在于 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)

我希望这些内容可以对你有所帮助!


你能解释一下这个答案吗?看起来这可能是唯一可以帮助我的。谢谢。 - Chegon
您可以通过连续两次按下.press('down'),然后按下.press('enter')来访问上下文菜单。 - Richard Modad

3
你可以使用pyautogui实现相同的功能。假设你正在使用Windows。 -->pyautogui.position() (187, 567) #打印当前光标位置

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

-->pyautogui.click(button='right')

-->pyautogui.hotkey('ctrl', 'c') - 在键盘上按下Ctrl+C(复制快捷键)。
请参考下面的链接获取更多信息https://pyautogui.readthedocs.io/en/latest/keyboard.html

1
这是一个很好的答案,但我需要将其应用于无界面驱动程序。抱歉没有说明问题的细节。 - 강희명

-2

你必须先移动到想要执行上下文点击的元素位置

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.move_to_element(img).context_click().send_keys(Keys.ARROW_DOWN).send_keys(Keys.ARROW_DOWN).send_keys(Keys.RETURN).perform()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接