LoginSignup
2
0

More than 5 years have passed since last update.

gebでファイルをダウンロードする

Last updated at Posted at 2017-07-06

gebでダウンロードしようとしてボタンをクリックしても、ファイル保存ダイアログの「OK」をクリックできないため、ダウンロードできない。

browser.with {
    go 'https://docs.docker.com/docker-for-mac/install/'
    def applink = $('a',text:'Get Docker for Mac (Stable)')
    println "----- ${applink.@href}"
    applink.click()
}

Docker_dmg_を開く.png

DownloadDupport クラスの download() を使う。
The Book Of Geb - Direct Downloading

java.net.HttpURLConnection のインスタンスが返るので、 InputStream をそのまま保存すれば良い。

browser.with {
    go 'https://docs.docker.com/docker-for-mac/install/'
    def applink = $('a',text:'Get Docker for Mac (Stable)')
    println "----- ${applink.@href}"
    def conn = download(applink.@href)
    if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
        InputStream is = conn.getInputStream()
        OutputStream os = new File('./Docker.dmg').newOutputStream()
        os << is
        is.close()
        os.close()
    }
}

groovyスクリプト全体は以下。

geb_download_dmg.groovy
@Grab('org.gebish:geb-core:1.1.1')
@Grab('org.seleniumhq.selenium:selenium-firefox-driver:3.4.0')
@Grab('org.seleniumhq.selenium:selenium-support:3.4.0')
@Grab('io.github.bonigarcia:webdrivermanager:1.6.2')
@GrabExclude('org.codehaus.groovy:groovy-all')

import geb.*
import org.openqa.selenium.*
import org.openqa.selenium.remote.DesiredCapabilities
import org.openqa.selenium.firefox.FirefoxDriver
// https://github.com/bonigarcia/webdrivermanager
import io.github.bonigarcia.wdm.FirefoxDriverManager

import java.net.HttpURLConnection

//ドライバ読み込み
FirefoxDriverManager.getInstance().setup()
DesiredCapabilities capabilities = DesiredCapabilities.firefox()
capabilities.setCapability('marionette', true)

Browser browser = new Browser(driver:new FirefoxDriver(capabilities))

browser.with {
    go 'https://docs.docker.com/docker-for-mac/install/'
    def applink = $('a',text:'Get Docker for Mac (Stable)')
    println "----- ${applink.@href}"
    def conn = download(applink.@href)
    if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
        InputStream is = conn.getInputStream()
        OutputStream os = new File('./Docker.dmg').newOutputStream()
        os << is
        is.close()
        os.close()
    }
}

browser.quit()

追記

自分が書く前に記事がありました。
downloadBytes() で byte配列が返るそうです。
Gebでファイルをダウンロードする - 山pの楽しいお勉強生活

browser.with {
    go 'https://docs.docker.com/docker-for-mac/install/'
    def applink = $('a',text:'Get Docker for Mac (Stable)')
    println "----- ${applink}"
    def bytes = downloadBytes(applink.@href)
    new File('./Docker.dmg').newOutputStream().write(bytes)
}
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0