如何使用Python和Selenium通过向Firefox发送按键来保存web图像

如何使用Python和Selenium通过向Firefox发送按键来保存web图像,python,firefox,authentication,selenium,selenium-webdriver,Python,Firefox,Authentication,Selenium,Selenium Webdriver,我想使用Selenium与Firefox的Python绑定来保存一个web图像。此图像需要身份验证才能查看,我不知道如何让urllib处理此身份验证: IOError:[Errno socket error][SSL:CERTIFICATE\u VERIFY\u FAILED]证书验证失败(\u SSL.c:590) 我正在Firefox中加载图像(在浏览器中进行了身份验证),然后尝试使用Selenium的Python绑定在浏览器中保存图像 以下是代码的简化版本: from selenium i

我想使用Selenium与Firefox的Python绑定来保存一个web图像。此图像需要身份验证才能查看,我不知道如何让urllib处理此身份验证:

IOError:[Errno socket error][SSL:CERTIFICATE\u VERIFY\u FAILED]证书验证失败(\u SSL.c:590)

我正在Firefox中加载图像(在浏览器中进行了身份验证),然后尝试使用Selenium的Python绑定在浏览器中保存图像

以下是代码的简化版本:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
URL1 = "https://special.site.ch/webpic/ACR01.jpg"
driver = webdriver.Firefox()
driver.get(URL1)
感觉像是一种自然的进步的东西如下所示:

img = driver.find_element_by_xpath('/html/body/div[1]/img[1]')
src = img.get_attribute('src')
urllib.urlretrieve(src, "ACR01.png")
但是,由于上述身份验证原因,这不起作用。我现在想尝试的是有效地将
Ctrl
s
,然后将
Enter
发送到Firefox,以便使用浏览器保存图像(经过验证)

我怎么能这样做


编辑:下面描述了一个更详细的浏览器配置文件规范尝试,但是,浏览器继续显示脚本无法处理的对话框:

import os
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains

URL1 = "https://special.site.ch/webpic/ACR01.jpg"

Firefox_profile = webdriver.FirefoxProfile()
Firefox_profile.set_preference("browser.download.folderList", 2)
Firefox_profile.set_preference("browser.download.manager.showWhenStarting", False)
Firefox_profile.set_preference("browser.download.dir", os.getcwd())
Firefox_profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "image/jpeg")
driver = webdriver.Firefox(firefox_profile = Firefox_profile)
driver.get(URL1)

ActionChains(driver).send_keys(Keys.CONTROL, "s").perform()

让我们应用以下技巧:获取所需图像的
src
属性值,通过
get()
在浏览器中打开它并使用保存它:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

URL1 = "https://special.site.ch/webpic/ACR01.jpg"

driver = webdriver.Firefox()
driver.get(URL1)

img = driver.find_element_by_xpath('/html/body/div[1]/img[1]')
src = img.get_attribute('src')
driver.get(src)

driver.save_screenshot("download.jpeg")

非常感谢你的建议。它确实有效。如果能够访问实际文件就好了,但是使用Selenium似乎很难访问“保存”对话框。我可以想象使用
xdool
会有什么尴尬的事情,但是最好以某种方式将身份验证封装起来,以便与
urllib.urlretrieve
一起使用。不幸的是,这并没有保存实际图像,而是保存了一个屏幕截图,其中包含了图像周围的大量空间。这非常聪明