Skip to content

Instantly share code, notes, and snippets.

@LDuncAndroid
Created March 6, 2020 23:11
Show Gist options
  • Save LDuncAndroid/ca5e179639ebd51c20bd3f49414569ee to your computer and use it in GitHub Desktop.
Save LDuncAndroid/ca5e179639ebd51c20bd3f49414569ee to your computer and use it in GitHub Desktop.
Quick Selenium script in Kotlin to download photos from Shootproof albums
package com.beflukey.shootproofdownloader
import org.openqa.selenium.By
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.support.ui.ExpectedConditions.presenceOfAllElementsLocatedBy
import org.openqa.selenium.support.ui.WebDriverWait
import java.io.*
import java.net.URL
import java.time.Duration
fun main(args: Array<String>) {
val albums = args[0].split(",")
val outputDir = File(args[1])
val driver = ChromeDriver()
val wait = WebDriverWait(driver, Duration.ofSeconds(10).seconds)
try {
albums.forEach { album ->
driver.get(album)
val photoDivIds =
wait.until(presenceOfAllElementsLocatedBy(By.xpath("//div[starts-with(@id,'photoId')]")))
.map { photoDiv ->
photoDiv.getAttribute("id")
}
photoDivIds.forEach { photoDivId ->
println(photoDivId)
with(wait) {
until {
driver.findElementById(photoDivId).click()
wait
}.until {
it.findElement(By.className("photo-image"))
wait
}.until {
driver.findElement(By.tagName("img"))
}.getAttribute("src").let { url ->
downloadImageToDir(photoDivId, url, outputDir)
}
until {
driver.findElementByClassName("up-navigation-long-text").click()
wait
}.until {
it.findElement(By.className("photo-image")).isDisplayed
}
}
}
}
} finally {
driver.quit()
}
}
fun downloadImageToDir(photoId: String, url: String, dir: File) {
val inputStream: InputStream = BufferedInputStream(URL(url).openStream())
val out = ByteArrayOutputStream()
val buf = ByteArray(1024)
var n = 0
while (-1 != inputStream.read(buf).also { n = it }) {
out.write(buf, 0, n)
}
out.close()
inputStream.close()
val response = out.toByteArray()
val fos = FileOutputStream(dir.absolutePath + "/${photoId.substringAfter("photoId-")}.jpg")
fos.write(response);
fos.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment