如何使用RSelenium检查网页中是否存在元素?

如何使用RSelenium检查网页中是否存在元素?,r,rselenium,R,Rselenium,我一直在尝试从一个网站上获取房产清单数据,在这个网站上,有时会有一个“查看更多”按钮来加载更多结果,但有时却没有。在第一种情况下,我一直在使用下面的代码,它工作得很好。比如说, url<- "http://www.magicbricks.com/property-for-rent/residential-real-estate?bedroom=2&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,S

我一直在尝试从一个网站上获取房产清单数据,在这个网站上,有时会有一个“查看更多”按钮来加载更多结果,但有时却没有。在第一种情况下,我一直在使用下面的代码,它工作得很好。比如说,

  url<- "http://www.magicbricks.com/property-for-rent/residential-real-estate?bedroom=2&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment,Service-Apartment,Residential-House,Villa&cityName=Navi-Mumbai&Locality=Vashi"
  remDr$navigate(url)
  Sys.sleep(3)
  webElem <- remDr$findElement("css", "#viewMoreButton a")
  while(webElem$isElementDisplayed()[[1]]){
    tryCatch({
      Sys.sleep(1)
      webElem <- remDr$findElement("css", "#viewMoreButton a")
      webElem$clickElement()
    }, error=function(e){})
  }
  mb<- read_html(remDr$getPageSource()[[1]])

url添加if条件可以解决问题:

  url<- "http://www.magicbricks.com/property-for-rent/residential-real-estate?bedroom=4&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment,Service-Apartment,Residential-House,Villa&cityName=Navi-Mumbai&Locality=Vashi"
  remDr$navigate(url)
  Sys.sleep(3)
  if(length(remDr$findElements("css", "#viewMoreButton a"))!=0){
    while(webElem$isElementDisplayed()[[1]]){
      tryCatch({
      Sys.sleep(1)
      webElem <- remDr$findElement("css", "#viewMoreButton a")
      webElem$clickElement()
      }, error=function(e){})
    }
  }
  mb<- read_html(remDr$getPageSource()[[1]])

url在第二个示例中,没有可单击的ViewMore按钮page@jdharrison是的,那么它不应该跳过while循环中的代码并继续阅读本例中的页面吗?运行代码时,我得到:
Error:Summary:NoSuchElement
当我运行
webElem时
  url<- "http://www.magicbricks.com/property-for-rent/residential-real-estate?bedroom=4&proptype=Multistorey-Apartment,Builder-Floor-Apartment,Penthouse,Studio-Apartment,Service-Apartment,Residential-House,Villa&cityName=Navi-Mumbai&Locality=Vashi"
  remDr$navigate(url)
  Sys.sleep(3)
  if(length(remDr$findElements("css", "#viewMoreButton a"))!=0){
    while(webElem$isElementDisplayed()[[1]]){
      tryCatch({
      Sys.sleep(1)
      webElem <- remDr$findElement("css", "#viewMoreButton a")
      webElem$clickElement()
      }, error=function(e){})
    }
  }
  mb<- read_html(remDr$getPageSource()[[1]])