python - 如何使用 Python 和 Selenium 将击键发送到 Firefox 来保存网页图像

标签 python firefox authentication selenium selenium-webdriver

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

IOError: [Errno socket error] [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)

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

这是代码的缩短版本:

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

但是,由于提到的身份验证原因,这不起作用。我现在想尝试的是有效地向 Firefox 发送 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() 在浏览器中打开它并使用 save_screenshot()保存它:

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

关于python - 如何使用 Python 和 Selenium 将击键发送到 Firefox 来保存网页图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29447188/

相关文章:

python - 在 Django 模板中捕获异常

javascript - localForage 在 Chrome 中找到数据,在 Firefox 中找不到

javascript - 使用 Javascript 读取 Linux 系统文件?

html - HR 在 Firefox 中显示不同

javascript - 通过 AJAX 处理身份验证?

ruby-on-rails - 使用基本身份验证集成测试 Rails API

python - 是否可以在 matplotlib 中修补图像?

python - 在Python中: How do I convert a user input into a piece of code?

authentication - 为什么API网关和认证服务应该不同?

python - BeautifulSoup 如何在 <br> 标签后提取文本