首页 > 解决方案 > 如何使用 Robot Framework + Selenium Library 强制下载 PDF 附件?

问题描述

在我的测试自动化套件中,我需要强制下载 PDF 文件。有问题的文件是具有应用程序/八位字节流的 mime 类型的 PDF,此外,服务器分配

Content-Disposition: attachment;
X-Download-Options: noopen 

到文件。

单击链接时,会出现提示:

在此处输入图像描述

我知道初始化 Open Browser 关键字时可以设置的选项,所以我做了以下操作:

*** Settings ***
Library    SeleniumLibrary

*** Variables ***
${PREFERENCES}    set_preference("browser.download.dir",r"C:${/}DL");set_preference("browser.download.lastDir",r"C:${/}DL");set_preference("browser.download.folderList", 2);set_preference("browser.helperApps.alwaysAsk.force", False);set_preference("browser.helperApps.neverAsk.openFile", "application/octet-stream, application/pdf")


*** Test Cases ***
Initial Setup

*** Keywords ***
Initial Setup
    Open Browser    about:blank    Firefox    ff_profile_dir=${PREFERENCES}

但是,像这样设置首选项是不够的,提示仍然存在。但是当我调试自动化套件并在该浏览器实例中手动将 PDF 文件的选项更改为“保存文件”时: 在此处输入图像描述

有用。设置该选项后,名为 handlers.json 的文件将被更新:

{"defaultHandlersVersion":{"en-US":4},"mimeTypes":{"application/pdf":{"action":0,"extensions":["pdf"]}},"schemes":{"irc":{"stubEntry":true,"handlers":[null,{"name":"Mibbit","uriTemplate":"https://www.mibbit.com/?url=%s"}]},"ircs":{"stubEntry":true,"handlers":[null,{"name":"Mibbit","uriTemplate":"https://www.mibbit.com/?url=%s"}]},"mailto":{"stubEntry":true,"handlers":[null,{"name":"Yahoo! Mail","uriTemplate":"https://compose.mail.yahoo.com/?To=%s"},{"name":"Gmail","uriTemplate":"https://mail.google.com/mail/?extsrc=mailto&url=%s"}]}}}

使用 Selenium 初始化 Firefox 时如何设置该值?

我还尝试手动创建自定义 Firefox 配置文件,然后定义 Selenium 库以在 Open Browser 上读取该自定义配置文件,但这不是一个可行的选项,因为我不想将该自定义配置文件存储在版本控制系统中。

标签: selenium-webdriverrobotframeworkcontent-dispositionfirefox-profile

解决方案


只需添加到 ${PREFERENCES} : set_preference("pdfjs.disabled", True)


推荐阅读