首页 > 解决方案 > 当 Rselenium 返回错误“NoSuchElement”时继续循环搜索

问题描述

我使用 Rselenium 从网站上抓取广告中的“租金”信息。但是,似乎并非每个广告都包含租金信息。因此,当我的循环运行到那些没有租金信息的人时,它会遇到错误,即“NoSuchElement”并且循环停止。我想要:

1/ 在没有租金信息的情况下填写“NA”值;和

2/ 继续循环以抓取租金信息。

我已经尝试过“tryCatch”功能,但是,它似乎不起作用。R 仍然给我一个错误,即“错误:摘要:NoSuchElement 详细信息:使用给定的搜索参数无法在页面上找到一个元素。更多详细信息:运行 errorDetails方法”

我的代码在下面。感谢您的时间和帮助。

#add url
url <- "https://www.toimitilat.fi/toimitilahaku/?size_min=&size_max=&deal_type%5B%5D=1&language=fin&result_type=list&advanced=0&gbl=1&ref=main#searchresult"  
rD <- rsDriver()
remDr <- rD$client

remDr$navigate(url)

 <  for(i in 8:13){ 
  Sys.sleep(0.86)
  rent <- remDr$findElement(using = "css selector", paste("#objectList > div:nth-child(", i, ") > div.infoCont > div.priceCont", sep = ""))$getElementText()
  #checking if there is a rent or not
  if(!is.null(rent)){
    tryCatch({
      rent <- unlist(strsplit(rent[[1]][1], "\n"))
      rent_df <- rbind(rent_df, rent)
  }, error = function(e){
    return("NoSuchElement")
    i = i + 1
    })
  }
}
>

标签: r

解决方案


解决方案rvest应该更容易,但如果你想或需要使用RSelenium,这应该工作:

# Preparation
library(dplyr)                                     # required for bind_rows 

# add url
url <- "https://www.toimitilat.fi/toimitilahaku/?size_min=&size_max=&deal_type%5B%5D=1&language=fin&result_type=list&advanced=0&gbl=1&ref=main#searchresult"  
rD <- rsDriver()
remDr <- rD$client
remDr$navigate(url)

# Checking that rD and remDr objects exist and work
## If youg get an error here, that means that selenium objects doesn´t work - usually because ports are busy, selenium server or client have not been closed properly or browser drivers are out of date (or something else)
class(rD)
class(remDr)

# making separate function retrieving the rent and handling exceptions
giveRent <- function(i) {
  Sys.sleep(0.86)
  tryCatch( {
    rent <- remDr$findElement(using = "css selector", paste("#objectList > div:nth-child(", i, ") > div.infoCont > div.priceCont", sep = ""))$getElementText()
    rent <- unlist(strsplit(rent[[1]][1], "\n"))
    rent <- rent[2]}
    , warning = function(e){rent <<- NA}
    , error = function(e){rent <<- NA})
  return(rent)}

# adding rent to the dataframe in for-loop
rent_df <- c()
for(i in 1:33){rent_df <- bind_rows(rent_df, (data.frame(giveRent(i))))}
print(rent_df)

推荐阅读