5

I am trying to right click with mouse and click save as Image in selenium python. I was able to perform right click with follwing method, however the next action to perform right click does not work any more. How can I solve this problem?

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()
강희명
  • 143
  • 1
  • 3
  • 9
  • Is it a requirement that you must right click / save as, or are you just trying to get the image content by whatever means necessary? – cody Nov 23 '18 at 03:03
  • @cody I need right click /save as or using same session and cookies that selenium browser use when it downloads images not just simple urlretrieve function. – 강희명 Nov 23 '18 at 03:30

2 Answers2

4

The problem is that the send_keys() method, after having created the context menu, sends the keys to the window, and not to the menu. So, there is no way to access the menu items.

I had a similar problem with downloading a canvas created in a webpage. Finally, I was able to download the image executing a javascript. I created a download element in order to manage the image. As it was a canvas, I had previously to execute the toDataURL method. Here is my python code:

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)

I hope it may help!

TomB
  • 86
  • 4
3

You can do the same functionality using pyautogui. Assuming you are using Windows. -->pyautogui.position() (187, 567) #prints the current cursor position

-->pyautogui.moveTo(100, 200)#move to location where right click is req.

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

-->pyautogui.hotkey('ctrl', 'c') - Ctrl+C in keyboard(Copy shortcut)

Refer to below link for further https://pyautogui.readthedocs.io/en/latest/keyboard.html

  • 1
    This one is good answer However I need to apply it on the headless driver. Sorry for not state detail about question. – 강희명 Nov 23 '18 at 05:32