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

时间:2016-11-01 18:26:01

标签: r rselenium

我一直在尝试从网站上获取房源列表数据,有时会有一个“查看更多”按钮来加载更多结果,有时它不存在。在第一种情况下,我一直在使用以下代码,它工作正常。例如,

  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<- "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)
  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]])

此代码卡在“WebElem&lt; - renDr $ findElement()”行,并且不会向前移动或抛出错误。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

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

count