您的位置:首頁>正文

用R語言高效下載圖片,學會節省不少時間

參考杜雨的文章進行自己的實踐操作。 選擇的網站是 http://www.uisdc.com/22-stunning-free-photos-websites, 這是PPT大神阿文推薦的下載高清圖片的網址, 想著既然要操作, 就選擇自己需要的圖片吧~

具體代碼:

install.packages("downloader")library(rvest)library(downloader)library(dplyr)

由於downloader不屬於R中的基礎包, 所以在運用之前需要下載安裝包, 其餘幾個在之前練習中已經安裝好了。

接著隨機選取一張圖片, 右鍵選擇“檢查”, 在網頁右側會出現一個網頁結構資訊, 同時定位到這張圖片所在的位置, 如圖所示:

其中, “img”是指圖片, “str”是指圖片的位址。

而我們是需要下載全部的圖片, 所以還需要查看整體的網頁結果, 也就是說找出img所在的分區結構, 我的查找方法就是不斷的往上找, 例如順著前面的三角符號往上查找它的上一級, 就是img所在的分區結構“div”, 如圖所示:

於是, 寫入代碼:

url <- 'http://www.uisdc.com/22-stunning-free-photos-websites'picture<- read_html(url)%>% html_nodes("div.entry-content")%>%html_nodes("img")%>%html_attr("src")

代碼中“%>%”表示將左邊賦值為右邊, “url”是圖片所在的網址, “div.entry-content”圖片所在的分區結構位置, “img”意味著選擇了圖片資訊, “src”是圖片所在的位址。

查看前面十個圖片位址資訊:

> head(picture,10)[1] "http://image.uisdc.com/wp-content/uploads/2015/04/22-stunning-free-photos-websites-1.jpg"[2] "http://image.uisdc.com/wp-content/uploads/2015/04/fancycrave.jpg" [3] "http://image.uisdc.com/wp-content/uploads/2015/04/madeinmoments.png" [4] "http://image.uisdc.com/wp-content/uploads/2015/04/realistic-shots-photo.jpg" [5] "http://image.uisdc.com/wp-content/uploads/2015/04/snapographic.jpg" [6] "http://image.uisdc.com/wp-content/uploads/2015/04/designerspics.jpg" [7] "http://image.uisdc.com/wp-content/uploads/2015/04/goodstockphotos.jpg" [8] "http://image.uisdc.com/wp-content/uploads/2015/04/stokpic.jpg" [9] "http://image.uisdc.com/wp-content/uploads/2015/04/freenaturestock.jpg" [10] "http://image.uisdc.com/wp-content/uploads/2015/04/freemagebank.jpg" >

最後, 利用for迴圈語句和downloader包下載圖片:

for(i in 1:length(picture)){ download(picture[i],paste("F:/數據視覺化/Image/picture",i,".jpg",sep = ""), mode = "wb")}

最後的成果:

補充一點, 有時候用如下代碼會爬取到一些無法的網址資訊, 也就是說不是我們需要的網址。

url <- 'http://www.uisdc.com/22-stunning-free-photos-websites'picture<- read_html(url)%>% html_nodes("div.entry-content")%>%html_nodes("img")%>%html_attr("src")

這個時候我們可以用“stringr”這個包進行篩選所需的網址, 例如:

right = "https"picture<-grep(right, picture,value=TRUE)

End.

運行人員:中國統計網小編(微信號:itongjilove)

中國統計網, 是國內最早的大資料學習網站, 公眾號:中國統計網

//www.itongji.cn

同類文章
Next Article
喜欢就按个赞吧!!!
点击关闭提示