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

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

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

   

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

谢谢

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

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

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

  public void getWindows() { Set windows = driver.getWindowHandles(); for (String window : windows) { driver.switchTo().window(window); System.out.println(driver.getTitle()); } } 

下载文件的非selenium解决方案是使用apache-commons库(creadits到盛源路 ):

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

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

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

那是对的。 有了Selenium,你就做不到。

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

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

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

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

一旦找到了你的url,其余的就是一个小路。 只需将URL下载到名为/pdfs的文件夹即可。 请参阅此问题以了解如何执行此操作。

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

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

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

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

如果您想使用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()