Rvest中存在vs.null

Rvest中存在vs.null,r,rvest,R,Rvest,我正在尝试编辑一个答案(),以便在删除它之前检查rvest中的元素是否存在 如果没有号码,我可以跳过phone元素,因为phone元素总是存在的(见下文) 但是“opening_hours”元素并不总是存在,所以我试图找到一种方法,如果元素不存在,则跳过它(因为否则代码会中断) 我想我可以在if语句中使用“exists”或“is.null”,但两者都失败了 site <- "https://concreteplayground.com/sydney/bars/chiswick-a

我正在尝试编辑一个答案(),以便在删除它之前检查rvest中的元素是否存在

如果没有号码,我可以跳过phone元素,因为phone元素总是存在的(见下文)

但是“opening_hours”元素并不总是存在,所以我试图找到一种方法,如果元素不存在,则跳过它(因为否则代码会中断)

我想我可以在if语句中使用“exists”或“is.null”,但两者都失败了

site <- "https://concreteplayground.com/sydney/bars/chiswick-at-the-gallery"

get_phone <- function(url) {
  webpage <- url %>% read_html()
  phone <- webpage %>% html_nodes('span[itemprop="telephone"]') %>% html_text()
  if(is_empty(phone)) phone = "NA"
  opening_hours <- webpage %>% 
    html_nodes('div.open-hours') %>% 
    html_attr('data-times') %>% jsonlite::fromJSON()
  data.frame(webpage = url, phone_number = phone, opening_hours = opening_hours, stringsAsFactors = FALSE)
}

get_phone(site)
站点%
html_attr('data-times')%%>%jsonlite::fromJSON()
data.frame(网页=url,电话号码=电话,营业时间=营业时间,stringsAsFactors=FALSE)
}
获取电话(站点)

一种可能的策略是使用
html\u node()
函数而不是
html\u nodes()
。这两个函数之间的区别是
html\u node()
将始终返回1个值。如果节点不存在,则
html\u node()
将返回NA。
然后可以检查NA并进行相应处理

library(rvest)

#url<-"https://concreteplayground.com/sydney/restaurants/north-sandwiches-cafe"
url<-"https://concreteplayground.com/sydney/bars/chiswick-at-the-gallery"

page<-read_html(url)
hours <- page %>% html_node("div.open-hours") 
   
if (!is.na(hours) ) {
   openhours<-hours %>% html_attr('data-times') %>% jsonlite::fromJSON()
   print(openhours)
} else {
   openhours <- NA
   print("no hours found")
}
库(rvest)
#网址