download.file() 无法下载网络图片
- 已编辑
> bd <- '1994-9-22 20:30:00'
> bdtime <- strptime(x = bd, format = '%Y-%m-%d %H:%M:%S', tz = "Asia/shanghai")
> unlist(unclass(bdtime))
sec min hour mday mon year wday yday isdst zone gmtoff
"0" "30" "20" "22" "8" "94" "4" "264" "0" "CST" NA
这是提取时间的年月日时分秒代码,但是我发现其中有个问题就是,提取的月份总是比实际月份少了一个月,不知道这是不是软件bug,还是另有说法呢?
奇怪奇怪,少见则多怪!
- 已编辑
事实上看了一下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
另外环境变量这个东西windows用户基本接触不到,隐藏的很深,设置起来也非常之麻烦,
参考 https://jingyan.baidu.com/article/00a07f3876cd0582d128dc55.html
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路径没有正确添加到环境变量里。上面我说了:
添加完之后在 cmd 里运行一下 curl。如果能运行,说明添加成功了。
添加路径到环境变量的方法,网上随便一搜一大堆。这里简述如下:
- 选中“此电脑”,右键选择“属性”,点击左侧“高级系统设置”,接着点击“高级”下的“环境变量”。
- 选中“系统变量”窗口里的“path”,点击“编辑”,然后点击“新建”。
- 将你的 curl.exe 文件所在文件夹的完整路径粘进去。举例来说,假如你的
curl.exe
在D:\CRUL\curl-7.64.1-win64-mingw\bin\curl.exe
,那么路径就是D:\CRUL\curl-7.64.1-win64-mingw\bin\
。点击确定。至此,已经添加完毕。 - 为了保险起见,测试一下是否添加成功。点击 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 我现在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包,发现下载其它包时能正常下载安装。