• R语言
  • download.file() 无法下载网络图片

junfei

事实上看了一下download.file的帮助,window的method改成"wininet"应该就行了

不过我测了一下,这样下载下来的文件会报错,换成curl::curl_download()就行,你可以试试装一下curl这个包
install.packages("curl")

代码

urlink <- 'http://www.biomet.co.at/pictures/'
aa <- readLines(urlink, encoding = 'UTF-8')
linkformat <- '/wp-content/gallery/.*jpg.*'
bb <- aa[grep(linkformat, aa)]

bb.jpgs = gsub(".*(http.*?.jpg).*","\\1", head(bb))

dir.create("c:/r4r")

lapply(bb.jpgs, function(fn){
  curl::curl_download(fn, destfile = paste0("c:/r4r/",basename(fn)))
})

junfei
时间的话

在help("DateTimeClasses")里写的是

mon
0–11: months after the first of the year.

如果要提取时间,建议使用lubridate包,

比如

lubridate::month(strptime("1994-9-22", format = "%Y-%m-%d"))
#> [1] 9

<sup>Created on 2019-03-31 by the reprex package (v0.2.1)</sup>

    junfei 在我这里测试,只要把 curl 的路径加到系统的环境变量里,就迎刃而解了。照tctcab 给的链接做就行。

    tctcab 我觉得不算复杂,作为 R 语言的 Windows 用户,还是应该了解一下为好,说不定就被逼进了 linux 阵营。

    method 上面我说了,用别的值在windows下载的图片打不开。

      junfei 不相关的问题最好新开一帖。月份是从 0 算起的。不知道为什么。

      tctcab 我是能不用额外包就不用。
      format(strptime("1994-9-22", format = "%Y-%m-%d"), format = "%m") 就够了吧。

      dapengde 已把curl路径加到了系统的环境变量中D:\CRUL\curl-7.64.1-win64-mingw\bin\curl.exe,然后试运行了代码,发现还是老样子报错!这个问题还竟无可奈何呀!

        junfei

        按我上面的代码装curl包试试,应该会自动帮你弄好curl路径什么的

          junfei

          要添加的路径应该是 D:\CRUL\curl-7.64.1-win64-mingw\bin\,不是 D:\CRUL\curl-7.64.1-win64-mingw\bin\curl.exe。

          添加完之后在 cmd 里运行一下 curl。如果能运行,说明添加成功了。

            tctcab 摁摁,安装了curl包后可以正常下载图片了,谢谢您啦!时间提取包我会去尝试的,谢谢前辈您的指点啦!
            dapengde 也非常谢谢赵老师的悉心指点!对于默认的月份都是从0开始的话那也就不足为奇了,只是对初学的我来说确实也是疑惑了些!现在明了,谢谢您!

            dapengde
            摁,按您指点改了路径之后在cmd中运行了...\bin\curl.exe,显示出如下一行代码:
            curl:try ‘curl--help’ or 'curl--manual' for more information
            然后在Rstudio中运行之前代码,报错依旧不肯罢休呢!

            > bb
            [1] NA
            > length(bb)
            [1] 1

              dapengde
              cmd 只运行curl的话,则运行不了!显示:curl不是内部或外部命令,也不是可运行的程序或批处理文件

                junfei 这说明你的curl路径没有正确添加到环境变量里。上面我说了:

                添加完之后在 cmd 里运行一下 curl。如果能运行,说明添加成功了。

                添加路径到环境变量的方法,网上随便一搜一大堆。这里简述如下:

                1. 选中“此电脑”,右键选择“属性”,点击左侧“高级系统设置”,接着点击“高级”下的“环境变量”。
                2. 选中“系统变量”窗口里的“path”,点击“编辑”,然后点击“新建”。
                3. 将你的 curl.exe 文件所在文件夹的完整路径粘进去。举例来说,假如你的 curl.exeD:\CRUL\curl-7.64.1-win64-mingw\bin\curl.exe,那么路径就是 D:\CRUL\curl-7.64.1-win64-mingw\bin\。点击确定。至此,已经添加完毕。
                4. 为了保险起见,测试一下是否添加成功。点击 windows 开始菜单的 windows 小图标,输入 cmd,回车,会打开命令提示符窗口。输入 curl,回车,如果出现 curl:try ‘curl--help’ or 'curl--manual' for more information,则说明添加成功。

                windows 10 按上述步骤操作就行。 windows 7 及更早的版本,在上面第 3 步之后需要重启一下 windows 才能生效。

                添加路径到环境变量的意义在于,你的 curl.exe 虽然住进硬盘里了,但 Windows 不认识去它家的路。添加路径到环境变量之后,你再让 Windows 去找 curl.exe,Windows 就知道路了。

                  dapengde 更改标题为「download.file() 无法下载网络图片

                  dapengde 我现在curl运行出现curl:try ‘curl--help’ or 'curl--manual' for more information了!
                  然后运行代码情况依旧!似乎进入了curl的家门,家长意见很大呀,是不是没带礼物呀?哈哈

                  > urlink <- 'http://www.biomet.co.at/pictures/'
                  >  aa <- readLines(urlink, encoding = 'UTF-8')
                  Warning message:
                  In readLines(urlink, encoding = "UTF-8") :
                    incomplete final line found on 'http://www.biomet.co.at/pictures/'
                  >  linkformat <- 'src = "http://www.biomet.co.at/wp/wp-content/gallery'
                  >  bb <- aa[grep(linkformat, aa)]
                  >  
                  >    for(i in 1:length(bb))
                  +        bb[i] <- substring(
                  +            bb[i],
                  +            regexpr("http", bb[i])[1],
                  +            regexpr(".jpg\"", bb[i])[1] + 3)
                  >   
                  >  bb <- unique(bb)
                  >  bb
                  [1] NA
                  >  length(bb)
                  [1] 1

                  这一问题在下载其它文件时(先后换了几种能用的镜像站点)也有打不开链接的情况,不知这是否属于同一种情况呢?代码如下:

                  > if(!require(devtools))  install.packages("devtools")
                  > devtools::install_github('rstudio/blogdown')
                  Downloading GitHub repo rstudio/blogdown@master
                  Error in utils::download.file(url, path, method = download_method(), quiet = quiet,  : 
                    cannot open URL 'https://api.github.com/repos/rstudio/blogdown/tarball/master'

                  在运行这一代码不成后,我试下载了其它的R包,发现下载其它包时能正常下载安装。

                    dapengde aa 值运行后出现了如下代码:第一行看不到,中间我省略了很多没有复制。
                    [2] ""
                    [3] "<!--[if lt IE 7 ]> <html class=\"ie ie6 no-js\" lang=\"en-US\"> <![endif]-->"
                    [4] "<!--[if IE 7 ]> <html class=\"ie ie7 no-js\" lang=\"en-US\"> <![endif]-->"
                    [5] "<!--[if IE 8 ]> <html class=\"ie ie8 no-js\" lang=\"en-US\"> <![endif]-->"
                    [6] "<!--[if IE 9 ]> <html class=\"ie ie9 no-js\" lang=\"en-US\"> <![endif]-->"
                    [7] "<!--[if gt IE 9]><!-->"
                    [8] "<html class=\"no-js\" lang=\"en-US\">"
                    [9] "<!--<![endif]-->"
                    [10] "<!-- the \"no-js\" class is for Modernizr. -->"
                    [11] ""
                    [12] "<head id=\"www-biomet-co-at\" data-template-set=\"biomet-theme\" profile=\"http://gmpg.org/xfn/11\">"
                    [13] "<meta charset=\"UTF-8\">"
                    [14] ""
                    [15] "<!-- Always force latest IE rendering engine (even in intranet) & Chrome Frame -->"
                    [16] "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\">"
                    [17] "<title>"
                    [18] " Pictures - biomet innsbruck</title>"
                    [19] "<meta name=\"title\" content=\" Pictures - biomet innsbruck\">"
                    [20] ""
                    [21] "<meta name=\"google-site-verification\" content=\"\">"
                    [22] "<!-- Speaking of Google, don't forget to set your site up: http://google.com/webmasters -->"
                    ......
                    [995] " title=\"img_2874\""
                    [996] " alt=\"img_2874\""
                    [997] " src=\"http://www.biomet.co.at/wp/wp-content/gallery/vinschgau/thumbs/thumbs_img_2874.jpg\""
                    [998] " width=\"100\""
                    [999] " height=\"75\""
                    [1000] " style=\"max-width:none;\""
                    [ reached getOption("max.print") -- omitted 6882 entries ]

                      junfei 找到问题了:你的代码 src = "错了,应该是src="。等号前后无空格。

                      你干嘛往里加空格?

                      我看你第一帖里就是有这两个冗余空格的……弄了半天可能不是 curl 的锅……

                        dapengde
                        没错,都是空格惹的祸src = “sep= ” “这两个地方都是因为多了空格出现了各种错误,下面是sep=” “存在的错误:

                        curl: (23) Failed writing body (0 != 6655)
                        Error in download.file(url = bb[i], destfile = paste("c:/r4r/", stname[i],  : 
                          'curl' call had nonzero exit status

                        这两个地方的空格去掉之后,只要不上房揭瓦,真是想怎么玩就怎么玩!看来空格不是我想加就能任性加呀[笑哭]谢谢您的悉心解惑啦!

                        [1] "88 of 597 downloaded."
                        curl: (3) URL using bad/illegal format or missing URL
                        Error in download.file(url = bb[i], destfile = paste("c:/r4r/pic/", stname[i],  : 
                          'curl' call had nonzero exit status

                        突发情况,下载到中途还是出现了问题,curl开始第三次循环下载时,突然连接不到链接了!本以为是高枕无忧了,中间只是自己新建了个文件夹pic,不知是不是又哪多了空格不是?源代码如下:

                         urlink <- 'http://www.biomet.co.at/pictures/'
                         aa <- readLines(urlink, encoding = 'UTF-8')
                         linkformat <- 'src="http://www.biomet.co.at/wp/wp-content/gallery'
                         bb <- aa[grep(linkformat, aa)]
                         for(i in 1:length(bb))
                               bb[i] <- substring(
                                   bb[i],
                                   regexpr("http", bb[i])[1],
                                   regexpr(".jpg\"", bb[i])[1]+3)
                         bb <- unique(bb)
                         length(bb)
                         dir.create('c:/r4r/pic/')
                         writeLines(bb, 'c:/r4r/pic/links.txt')
                         
                         stname <- substring(bb, 47, 50)
                         stname <- stname[-which(stname == '')]
                         for(i in unique(stname))
                             dir.create(paste('c:/r4r/pic/', i, sep = ''))
                         
                         for(i in 1:length(bb)) {
                               download.file(
                                 url = bb[i],
                                 destfile = paste(
                                 'c:/r4r/pic/', stname[i],'/', stname[i], i, '.jpg',
                                 sep = ""),
                                 method = 'curl', quiet = TRUE)
                               print(paste(i, 'of', length(bb), 'downloaded.'))
                             }

                        经还原为原来文件夹路径的代码运行,依旧出现下载第88张照片之后就报错!可见也不是这个原因,代码也再次检查了应该是没有任性的添加空格了。

                          junfei 把下面这两行:

                           stname <- substring(bb, 47, 50)
                           stname <- stname[-which(stname == '')]

                          改为:

                          bb <- bb[bb != '']
                          stname <- substring(bb, 47, 50)
                          stname <- stname[stname != '']

                          原因是这个网页更新了,图片文件扩展名除了 .jpg 还增加了 .jpeg 以及 .JPG,而原来的代码没考虑这个情况。

                          为了改动最小,修改后的代码只下载 .jpg。