【问题标题】:How to right click in selenium and click save image as in python如何右键单击硒并单击将图像保存为python
【发布时间】:2019-04-25 16:14:06
【问题描述】:

我正在尝试用鼠标右键单击并单击在 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 我需要右键单击 /save as 或使用 selenium 浏览器在下载图像时使用的相同会话和 cookie,而不仅仅是简单的 urlretrieve 功能。

标签: python selenium web-crawler


【解决方案1】:

问题是 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)

希望对你有帮助!

【讨论】:

  • 你能解释一下这个答案吗?看来这是唯一可以帮助我的。坦克。
【解决方案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

【讨论】:

  • 这是一个很好的答案但是我需要将它应用到无头驱动程序上。很抱歉没有详细说明问题。
【解决方案3】:

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

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

【讨论】:

    猜你喜欢
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    相关资源
    最近更新 更多