馥滢( '▿ ' ) 2022-12-17 16:26 采纳率: 100%
浏览 31
已结题

Error in `str_split()`: ! `string` must be a vector, not a <xml_nodeset> object. R语言抓取历史天气数据


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语言抓取历史天气数据,结果报这样的错,能不能帮忙看一下啊,这个要怎么解决啊
或者是有没有其他抓取历史天气方法啊

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 12月25日
    • 创建了问题 12月17日

    悬赏问题

    • ¥15 Opencv(C++)异常
    • ¥15 VScode上配置C语言环境
    • ¥15 汇编语言没有主程序吗?
    • ¥15 这个函数为什么会爆内存
    • ¥15 无法装系统,grub成了顽固拦路虎
    • ¥15 springboot aop 应用启动异常
    • ¥15 matlab有关债券凸性久期的代码
    • ¥15 lvgl v8.2定时器提前到来
    • ¥15 qtcp 发送数据时偶尔会遇到发送数据失败?用的MSVC编译器(标签-qt|关键词-tcp)
    • ¥15 cam_lidar_calibration报错