如何右键单击硒并单击将图像另存为python

时间:2018-11-23 02:47:34

标签: python selenium web-crawler

我试图用鼠标右键单击,然后单击硒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()

3 个答案:

答案 0 :(得分:2)

您可以使用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 :(得分:1)

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

我在下载在网页中创建的画布时遇到了类似的问题。最后,我能够下载执行javascript的图像。我创建了一个download元素来管理图像。由于它是画布,因此我以前必须执行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)

我希望它会有所帮助!

答案 2 :(得分:0)

requires function_body_compiles