r - 当 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
})
}
}
>
解决方案
解决方案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)
推荐阅读
- android - 在自身内部更新(或创建)流并发出这个、Room、Flow、MVVM
- button - 页面控制器发生了变化,但 Carousel 没有 SwiftUI
- c - #define N 500 错误:预期标识符或数字前的“(”
- javascript - Javascript 在 OnClick (HTML/PHP) 上发送两个参数
- python - ScikitLearn,如何在外部数据集上使用局部线性嵌入
- java - 如何在java中传递可选参数
- html - 不显示下拉菜单,即使它适用于具有几乎相同 CSS 的其他页面
- php - Laravel:在保存到数据库之前从 jQuery UI Datepicker 将 m/d/Y 转换为 Ymd
- angular - mat-form-field legacy 更改边框颜色
- c++ - 这是 g++ for 循环实现还是我的代码中的错误