Biraj kandel
Biraj kandel

Reputation: 9

How can I download multiple jpeg files from an url in R?

I need to download multiple .jpg files that has "*b13" in filename in the url below. Can anyone help me how to list the file names and download them in a folder? https://www.data.jma.go.jp/mscweb/data/himawari/list_ha2.html

install.packages("jpeg")
library(jpeg)
install.packages("here")
library(here)
myurl <- "https://www.data.jma.go.jp/mscweb/data/himawari/list_ha2.html"
for (i in 1:138) { 
myurl <- paste(myurl[i,1], sep = "")
z <- tempfile()
download.file(myurl,z,mode="wb")
pic <- readJPEG(z)
writeJPEG(pic,here("Q:\\R_himawari"), paste("image", "i", ".jpg") 
          file.remove(z)
                 }

Upvotes: 0

Views: 81

Answers (1)

QHarr
QHarr

Reputation: 84465

You can use an attribute = value CSS selector to select the href of interest by the substring "b13". The [href*=b13] targets href attributes containing the characters "b13". Use url_absolute() to complete the paths to the source image files. Then download those files. i can come from the loop and should not be a hard-coded string/character "i".

install.packages("jpeg")
library(jpeg)
install.packages("here")
#library(here)
library(magrittr)
library(rvest)


myurl <- "https://www.data.jma.go.jp/mscweb/data/himawari/list_ha2.html"

links <- read_html(myurl) %>%
  html_elements("table [href*=b13]") %>%
  html_attr("href") %>%
  url_absolute(myurl)

for (i in seq_along(links)) {
  z <- tempfile()
  download.file(links[i], z, mode = "wb")
  pic <- readJPEG(z)
  # writeJPEG(pic, paste0(Q:/R_himawari/", "image_", i, ".jpg")
  writeJPEG(pic, paste0("C:/Users/User/DestinationFolder", "/image_", i, ".jpg"))
  file.remove(z)
}

Upvotes: 0

Related Questions