download.file() 无法下载网络图片
- 已编辑
junfei 这里包含了两个问题。
第一,'文件却显示为空'。
这是因为代码的第二行并未生效,并未把网页读进来。原因如 @tctcab 所言,可能是因为你用的是 windows 操作系统,而你的操作系统里没有安装 curl。所以,单单是为了这一行生效的话,需要改成:
aa <- readLines(url(urlink), encoding = 'UTF-8')
第二,'curl' call had nonzero exit status
。
这是因为,当运行到 download.file
时,由于你没有装 curl,所以 method = 'curl'
无法生效。你可以把 method = 'curl'
去掉,这样,图片虽然可以下载,但是打开时会有问题。我不知道这是 windows 的问题还是图片浏览软件的问题,没有深究。我试过了method
取其他值,得到的图片都没法在 windows 下正常浏览。
要解决这个问题,需要安装 curl。如果安装了 curl,那么书里的代码(包括第一个问题)不需要更改,可以正常运行。
抱歉,写书的时候没有注意到这一点,想来是当时我的电脑里已经装好了 curl。
- 已编辑
dapengde 感觉也不是有没有curl的问题!我直接复制了这两个链接到浏览器中,第一个链接能打开,第二个链接不能。我删除了下载的curl,R中也有curl这个功能,同样显示的是第一个链接能打开,第二个链接不能。代码如下:
> curl::curl("http://www.biomet.co.at/pictures/", open = "r")
A connection with
description "http://www.biomet.co.at/pictures/"
class "curl"
mode "r"
text "text"
opened "opened"
can read "yes"
can write "no"
> curl::curl("http://www.biomet.co.at/wp/wp-content/gallery", open = "r")
Error in open.connection(con, open = mode) : HTTP error 403.
估计是因为服务器的原因,第二个链接在我这打不开,所以才有之前的两个问题。
- 已编辑
> 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>