Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么rvest在包含在循环中时会提取空数据?_R_Rvest - Fatal编程技术网

为什么rvest在包含在循环中时会提取空数据?

为什么rvest在包含在循环中时会提取空数据?,r,rvest,R,Rvest,我正试图从tripadvisor上获取某家酒店的酒店评论。我正在使用Rvest来实现我的目标。此脚本必须刮取多个页面 在执行脚本时,在循环中执行时,rvest有时返回带有空值的向量。这完全是随机的。有人对此有办法吗 我试着用手在剧本中穿行。当我慢慢地通过它时,它大部分时间都在工作,但有时仍然设法提取空数据 # Webscrapen df <- data.frame() x = 0 for(i in 1:250){ url <- paste("https://www.tripad

我正试图从tripadvisor上获取某家酒店的酒店评论。我正在使用Rvest来实现我的目标。此脚本必须刮取多个页面

在执行脚本时,在循环中执行时,rvest有时返回带有空值的向量。这完全是随机的。有人对此有办法吗

我试着用手在剧本中穿行。当我慢慢地通过它时,它大部分时间都在工作,但有时仍然设法提取空数据

# Webscrapen
df <- data.frame()
x = 0

for(i in 1:250){
  url <- paste("https://www.tripadvisor.com/Hotel_Review-g295424-d7760386-Reviews-or",x,"-Hyatt_Regency_Dubai_Creek_Heights-Dubai_Emirate_of_Dubai.html", sep = "")
  x = x + 5

  reviews <- url %>%
    read_html() %>%
    html_nodes('.common-text-ReadMore__content--2X4LR') %>%
    html_node('.hotels-hotel-review-community-content-review-list-parts-ExpandableReview__reviewText--2OVqJ span') %>%
    html_text()

  rating <- url %>%
    read_html() %>%
    html_nodes(".hotels-hotel-review-community-content-review-list-parts-RatingLine__bubbles--3d2Be span") %>%
    html_attr("class")

  rating <- sapply(strsplit(rating, "_"), `[`, 4) %>% 
    as.numeric()

  if(nrow(df) == 0){
    df <- data.frame(reviews[!is.na(reviews)], rating, stringsAsFactors = F)
  } else {
    temp <- df
    df <- rbind(temp, data.frame(reviews[!is.na(reviews)], rating, stringsAsFactors = F))
  }
}
#Webscrapen
df%
html_节点('.hotels-hotel-review-community-content-review-list-parts-ExpandableReview__-reviewText--2OVqJ span')%>%
html_text()
评级%
读取html()%>%
html_节点(“.hotels-hotel-review-community-content-review-list-parts-RatingLine_u气泡--3d2Be span”)%>%
html_属性(“类”)
评级%
as.numeric()
如果(nrow(df)==0){

df我找到了一个解决方法,将评论放在一个重复循环中,只要向量没有填充,就一直重复

代码执行时间稍长,但它完成了任务

  repeat{
    Review <- url %>%
      read_html() %>%
      html_nodes('.common-text-ReadMore__content--2X4LR') %>%
      html_node('.hotels-hotel-review-community-content-review-list-parts-ExpandableReview__reviewText--2OVqJ span') %>%
      html_text()
    if(length(Review) >= 1 ){
      break;
    }
  }  
重复{
审查%
读取html()%>%
html_节点('.common-text-ReadMore_u内容--2X4LR')%>%
html_节点('.hotels-hotel-review-community-content-review-list-parts-ExpandableReview__-reviewText--2OVqJ span')%>%
html_text()
如果(长度(审查)>=1){
打破
}
}