如何保存在没有网址的浏览器窗口中弹出的.pdf文件?

时间:2013-09-23 20:15:26

标签: java javascript selenium

我正在使用我公司网站上提供的.pdf个文件。我不知道有任何方法可以下载它们并存储在一个文件夹中。

我单击以获取.pdf文件的链接具有以下源代码:

  <a href="javascript:propertiesView('documentName')">

当我点击链接时,会在新的浏览器窗口中弹出一个.pdf文件,其中没有网址,也没有源代码。我认为没有办法直接操纵.pdf,然后如何保存它以便操作文件夹中的.pdfs

谢谢

3 个答案:

答案 0 :(得分:3)

您可以通过简单地告诉浏览器始终将PDF文件保存到磁盘(信用到Dirk)来获得好运:

firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");

如果这不起作用,您可能可以使用switchTo()方法遍历所有打开的窗口/选项卡。尝试使用这样的方法来了解您打开的窗口(Prashant Shukla的信用):

    public void getWindows() {
        Set<String> windows = driver.getWindowHandles();

        for (String window : windows) {
            driver.switchTo().window(window);
            System.out.println(driver.getTitle());
        }
    }

下载文件的非硒解决方案是使用apache-commons库(creadits to Shengyuan Lu):

org.apache.commons.io.FileUtils.copyURLToFile(URL, File)

但这需要您知道窗口的URL,您可以使用我提到的第二种方法(driver.switchTo())和driver.getCurrentUrl()来获取该窗口。

答案 1 :(得分:2)

  

我认为没有办法直接操纵.pdf

这是对的。有了Selenium,你就不能。

  

如何保存它以便从文件夹中操作.pdfs?

我实际上已经在我工作的回归系统中实现了这一点。

我的第一步是根据propertiesView()构建一个Url。方法做了。

在你的情况下,propertiesView()确实有某种window.open。所以你的目标是,提取它打开的Url,并使用连接来构建url。

找到你的网址后,剩下的就是蛋糕。只需将网址下载到名为/pdfs的文件夹即可。有关如何执行此操作,请参阅this question

甚至可能需要调用该方法来解决问题。由于我对您的系统测试无知,除非您发布它,否则我很难给您一个代码答案。

我告诉你的一个提示是,如果你使用的是Selenium 1,请使用

String url =selenium.getEval("var url = something; url;");

获取url并将其转换为java对象。 (如果使用硒2,请使用JavaScriptExecutor#executeScript

答案 2 :(得分:2)

如果您想使用selenium将PDF保存到IE中的硬盘驱动器,则需要使用pywinauto和selenium。我只是将这段代码用于在浏览器中打开的PDF文件。

//selenium imports
from pywinauto import application //pywinauto import

//write selenium code to open up pdf in the browser 
driver = webdriver.Ie("IEDriverServer.exe", capabilities = caps)

//this could be a get or driver.execute_script() to click a link
driver.get("link to pdf")

//save pdf
app = application.Application()

//get the ie window by the title of the application (assuming only one window is open here)
ie =  app.window_(title_re = ".*Internet Explorer.*")

//this line focuses on the pdf that is open in the browser
static = ie.Static

//focus on the pdf so we can access the internal controls
static.SetFocus()

//control + h shows the pdf bar, but you don't really need this step 
//for it to work. i just used it as a debug
static.TypeKeys("^H")

//open save file dialog
static.TypeKeys("+^S")

//tricky here because the save file dialog opens up as another app instance   
//which is how pywinauto sees it
app2 = application.Application()

//bind to the window by title - name of the dialog
save = app2.window_(title_re = ".*Save As.*")

//this is the name of the property where you type in the filename
//way to be undescriptive microsoft
file_name = save[u'FloatNotifySink']

//type in the file name
save.TypeKeys("hello")

//pause for a second - you don't have to do this
time.sleep(4)

//find and bind the save button
button = save[u'&SaveButton']

//click the save button
button.Click()
相关问题