用R语言抓取历史天气数据
中国城市历史数据网保存有从2011年1月1日起的历史数据,包括天气、高低温以及风向和风力,对于需要分析气象数据又苦于无法得到数据的研究人员,爬取数据不失为一个办法中的办法。但是网上爬取数据的又多为Python,用R语言的较少,可能和R的爬取能力较弱有关吧。但是对于习惯了R的人,还是需要一个用R编写的爬虫踏实些。。。下面就为大家送上相应的R代码。
需要爬取的网页是这样的::
http://www.tianqihoubao.com/lishi/kangding/month/201707.html
以下是相应的R程序。可以修改成自己需要爬取的城市、时间段以及保存的文件名。
#加载网页抓取程序包与数据清理程序包,报错需要安装相应的程序包
library(rvest)
library(plyr)
library(stringr)
#设定装载天气数据的数据包
tdata=data.frame()
#设定抓取的城市,这里设定为四川省康定市
city <- ‘kangding’
#设定抓取的年份,从11年一直到19年
y<-c(“11”,“12”,“13”,“14”,“15”,“16”,“17”,“18”,“19”)
#设定抓取的月份,共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-9]{8}",date.line))[[1]][1])
wea<-content[i*4+2]
wea<-str_trim(unlist(str_split(wea,"\r\n")))
wea<-gsub("
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)
}
}}
#保存文件到E盘
write.csv(tdata,“E:/kangding_weather.csv”)