开发者

Saving contents of a browser window to disk

开发者 https://www.devze.com 2023-03-28 10:34 出处:网络
I was just wondering if there\'s an elegant way to save the browser contents (in my case a pdf file) to disk using a browser automated via Watir (navigate to a page, then \"click\" on a link to a pdf

I was just wondering if there's an elegant way to save the browser contents (in my case a pdf file) to disk using a browser automated via Watir (navigate to a page, then "click" on a link to a pdf document)? I was hoping to do a "sen开发者_JS百科d_keys" on the browser object but it doesn't seem to work -- browser.send_keys("+^S"). I could use AutoIt but that requires that I find a window first (or did I get that wrong?) by title and I find that approach not quite reliable (in case there happens to be duplicate windows...)

Here's what the code looks like...

b=Watir::Browser.new
b.goto "http://somesite.com/somepage.htm" #assume this page contains a bunch of links
b.link(:text, /pdf/i).when_present.click #this action loads the pdf in the browser
b.send_keys("+^s") #try to invoke acrobat's "save as" <-- does NOT work! 

The last line probably does not work because the Acrobat control may not be in focus and may not be receiving the intended keystrokes...

I know there are several options here as pointed out by Zeljko. But I was wondering how come I don't have access to the underlying document stream?


To quote myself:

The easiest solution is to disable the popup and download the file automatically.

There are other solutions too: http://wiki.openqa.org/display/WTR/File+Downloads


I was successfull to send Ctrl-S to the browser (tested with firefox) with:

b.send_keys([:control, 's'])

But it does not help really. After this you are in the "Save As"-dialogue. But you will not save the PDF, but the whole Website (maybe it depends on your browser settings).

To control this save as dialogue I used AutoIt:

    require 'win32ole'  #For AutoIt
    au3 = WIN32OLE.new("AutoItX3.Control")
    wintitle = "Speichern unter"  #<-- adapt language specific text
    download_directory = File.join(Dir.pwd, "downloads")
    win_exists = au3.WinWait(wintitle, nil, 5)   
    if (win_exists > 0)
      au3.WinActivate(wintitle)
      au3.Send('!n')  #Dateiname
      au3.Send(download_directory.gsub(/\//, '\\'))
      sleep 1
      au3.Send('{ENTER}')
    end

Now I have a directory with containing my pdf and I can do:

    pdf_mask = "%s-Dateien/*.pdf" % download_directory #<- Again language specific
    Dir[pdf_mask].each{|pdf|
      #do something twith the file
    }      

I'm new to AutoIt, maybe I find an easier way.

But I agree to the other answer:

The easiest solution is to disable the popup and download the file automatically.

0

精彩评论

暂无评论...
验证码 换一张
取 消