R语言获取网页快照

今天给大家介绍一个在R中的神器-网页快照获取。这个包可以进行批量获取网页并转化为图像,那这功能有啥用呢,大家可以开动脑筋想想,反正和shiny配合起来那是很好玩的。

首先我们看下包的安装:

代码语言:javascript
复制
install.packages("webshot")

接下来我们直接通过实例来看下具体的使用方式:

代码语言:javascript
复制
###安装依赖的包
webshot::install_phantomjs()
代码语言:javascript
复制
##参数默认的快照
webshot("https://github.com/rstudio/shiny")#保存文件在当前目录中,并命名为webshot.png
代码语言:javascript
复制
##延长等待时间保证页面的完整性
webshot("https://github.com/rstudio/shiny",delay = 25)
代码语言:javascript
复制
##批量进行网页获取,将会进行以webshot000x进行排序命名
webshot(c("https://github.com/rstudio/shiny",
         "http://rstudio.github.io/leaflet"),
       delay = 0.5)

###当然也可以进行自定义命名,需要设置file,用一个向量来表示输出文件的名称列表

代码语言:javascript
复制
webshot(c("https://github.com/rstudio/shiny",
          "http://rstudio.github.io/leaflet"),file=c("a.png","b.png")
       ,delay = 0.5)
代码语言:javascript
复制
##当前屏幕的截取
webshot("http://rstudio.github.io/leaflet","leaflet-viewport.png",cliprect = "viewport")
代码语言:javascript
复制
###可以自己选取想要街区的矩形区域
webshot("http://rstudio.github.io/leaflet","leaflet-clip.png",
       cliprect = c(200, 5, 400, 300))
代码语言:javascript
复制
##通过CSS样式提取快照
webshot("http://rstudio.github.io/leaflet","leaflet-clip.png",selector = c("#next-steps"))
代码语言:javascript
复制
##如果区域小的话还可以进行扩展
webshot("http://rstudio.github.io/leaflet","leaflet-boxes.png",
       selector = "#installation", expand = c(10, 50, 0, 50))
代码语言:javascript
复制
##如果有的网站需要用户提供浏览器参数,那也是提供了这个功能

webshot(
"https://www.rstudio.com/products/rstudio/download/",
"rstudio.png",
useragent = "Mozilla/5.0 (Macintosh; Intel Mac OS X)"
)

####和shiny的交互两种方式

代码语言:javascript
复制
##1. 直接访问项目所在的目录
appdir <-system.file("examples", "01_hello",package="shiny")
#With a Shiny directory
appshot(appdir, "01_hello.png")
代码语言:javascript
复制
##2.通过正在运行的项目进行获取
shinyapp <- shiny::shinyAppDir(appdir)
appshot(shinyapp,"01_hello_app.png")
代码语言:javascript
复制
##其它的设置可以直接参考webshot获取在shiny中的任何元素。比如获取某个ID的截图:
appshot(appdir,"01_hello.png",selector="#distPlot")

当然如果获得的截图的文件太大,那需要进行压缩或者缩小比例需要用到函数

resize和shrink。

欢迎大家学习交流!