install.packages("rvest")
install.packages("plyr")
install.packages("stringr")
library(rvest)
library(plyr)
library(stringr)
#设定装载天气数据的数据包
tdata=data.frame()
#设定抓取的城市,这里设定为山东省潍坊市
city <- 'weifang'
#设定抓取的年份,从11年一直到22年
y<-c("11","12","13","14","15","16","17","18","19","20","21","22")
#设定抓取的月份,共12个月
m<-c("01","02","03","04","05","06","07","08","09","10","11","12")
for (j in 1:length(y)){
for (k in 1:length(m)){
date <- paste0("20",y[j],m[k])
#设定历史天气的url
baseUrl <- 'http://www.tianqihoubao.com/lishi/'
url <- paste(baseUrl, city, '/month/', date, '.html', sep = '')
content <- url %>% read_html(encoding='GBK') %>% html_nodes('td')
n<-length(content)
for(i in 1:(n/4-1)){
date.line<-content[i*4+1]
date<-as.numeric(regmatches(date.line,regexec("[0-12]{11}",date.line))[[1]][1])
wea<-content[i*4+2]
wea<-str_trim(unlist(str_split(wea,"\r\n")))
wea<-gsub("","",wea)
wea<-gsub("/","",wea)
wea1<-wea[2]
wea2<-wea[3]
temp.line<-content[i*4+3]
temp.line<-str_trim(unlist(str_split(temp.line,"\r\n")))
temp.line<-gsub("℃","",temp.line)
hightemp<-temp.line[2]
lowtemp<-temp.line[4]
wind<-content[i*4+4]
wind<-str_trim(unlist(str_split(wind,"\r\n")))
wind<-gsub("","",wind)
wind<-gsub("/","",wind)
wind1<-wind[2]
wind2<-wind[3]
hh<-data.frame(cbind(date,hightemp,lowtemp,wea1,wea2,wind1,wind2))
tdata<-rbind(tdata,hh)
}
}}
Error in str_split()
:
! string
must be a vector, not a object.
Run rlang::last_error()
to see where the error occurred.
用R语言抓取历史天气数据,结果报这样的错,能不能帮忙看一下啊,这个要怎么解决啊
或者是有没有其他抓取历史天气方法啊